在ActiveMQ中,CORE是最初实现的协议,而AMQP则是后来添加的协议。AMQP是一种标准开放性协议,为使用不同语言和框架的应用程序提供了可靠的异步消息传递。CORE协议则是ActiveMQ专有的协议,它使用jms框架并提供了广泛的功能和可用性。
以下是使用AMQP协议发送和接收消息的简单示例:
import org.apache.qpid.protonj2.client.*;
import org.apache.qpid.protonj2.types.messaging.Message;
public class AmqpProducer {
public static void main(String[] args) throws Exception {
String host = "localhost";
int port = 5672;
String address = "queue";
String messageBody = "Hello, AMQP!";
ProtonClientOptions options = new ProtonClientOptions().setSsl(false);
ProtonClient client = ProtonClient.create(options);
client.connect(host, port).block();
ProtonConnection connection = client.connect(host, port).block();
ProtonSender sender = connection.createSender(address);
Message message = Message.Factory.create();
message.setBody(messageBody);
sender.send(message).block();
sender.close();
client.close();
}
}
public class AmqpConsumer {
public static void main(String[] args) throws Exception {
String host = "localhost";
int port = 5672;
String address = "queue";
ProtonClientOptions options = new ProtonClientOptions().setSsl(false);
ProtonClient client = ProtonClient.create(options);
client.connect(host, port).block();
ProtonConnection connection = client.connect(host, port).block();
ProtonReceiver receiver = connection.createReceiver(address);
receiver.open().block();
Message message = receiver.receive().block();
if (message != null) {
System.out.printf("Message received: %s\n", message.getBody());
receiver.accept(message).block();
} else {
System.out.println("No message received.");
}
receiver.close();
client.close();
}
}
这些示例使用ProtonJ,这是一种使用AMQP 1.0协议与消息代理交互的Java库。这里的代码包括一个简单的生产者,它将一条消息发送到队列,并且一个简单的消费者来接收这条消息。这里的AMQP协议提供