第 4 章 例子
本章演示了通过示例程序使用红帽构建的 Apache Qpid ProtonJ2。
如需了解更多示例,请参阅 Apache Qpid ProtonJ2 示例。
4.1. 发送消息 复制链接链接已复制到粘贴板!
这个客户端程序使用 <server Host> 和 < serverPort> 连接到服务器,为目标 <address > 创建发件人,发送包含 String 和 exit 的 100 消息。
示例:发送消息
package org.apache.qpid.protonj2.client.examples;
import org.apache.qpid.protonj2.client.Client;
import org.apache.qpid.protonj2.client.Connection;
import org.apache.qpid.protonj2.client.ConnectionOptions;
import org.apache.qpid.protonj2.client.Message;
import org.apache.qpid.protonj2.client.Sender;
import org.apache.qpid.protonj2.client.Tracker;
public class Send {
private static final int MESSAGE_COUNT = 100;
public static void main(String[] argv) throws Exception {
final String serverHost = System.getProperty("HOST", "localhost");
final int serverPort = Integer.getInteger("PORT", 5672);
final String address = System.getProperty("ADDRESS", "send-receive-example");
final Client client = Client.create();
final ConnectionOptions options = new ConnectionOptions();
options.user(System.getProperty("USER"));
options.password(System.getProperty("PASSWORD"));
try (Connection connection = client.connect(serverHost, serverPort, options);
Sender sender = connection.openSender(address)) {
for (int i = 0; i < MESSAGE_COUNT; ++i) {
Message<String> message = Message.create(String.format("Hello World! [%s]", i));
Tracker tracker = sender.send(message);
tracker.awaitSettlement();
System.out.println(String.format("Sent message to %s: %s", sender.address(), message.body()));
}
}
}
}
<.> 红帽构建的 Apache Qpid ProtonJ2 所需的软件包。
<.> 要发送的消息数量。
< ;.> server host 是 AMQP 连接的主机或虚拟主机的网络地址,可通过设置环境变量 HOST 来配置。
<.> serverPort 是代理接受连接的主机上的端口,可通过设置环境变量 PORT 来配置。
< ;.& gt; 客户端是可创建多个到代理的连接的容器。
<.& gt; 选项 用于各种设置,包括 User 和 Password。请参阅 第 5.1 节 “连接选项” 了解更多信息。
<.& gt; 连接 是到代理的 AMQP 连接。
<.> 创建向代理传输消息的 发送者。
在消息 send loop 中创建了新消息。
<.> 消息发送到代理。
<.> 等待代理设置消息。
运行示例
要运行示例程序,请参阅 第 3 章 开始使用。