第 4 章 例子


本章演示了通过示例程序使用红帽构建的 Apache Qpid ProtonJ2。

如需了解更多示例,请参阅 Apache Qpid ProtonJ2 示例

4.1. 发送消息

这个客户端程序使用 <server Host> 和 &lt; 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; 
1


public class Send {

    private static final int MESSAGE_COUNT = 100; 
2


    public static void main(String[] argv) throws Exception {
        final String serverHost = System.getProperty("HOST", "localhost"); 
3

        final int serverPort = Integer.getInteger("PORT", 5672); 
4

        final String address = System.getProperty("ADDRESS", "send-receive-example");

        final Client client = Client.create(); 
5


        final ConnectionOptions options = new ConnectionOptions(); 
6

        options.user(System.getProperty("USER"));
        options.password(System.getProperty("PASSWORD"));

        try (Connection connection = client.connect(serverHost, serverPort, options); 
7

             Sender sender = connection.openSender(address)) {  
8


            for (int i = 0; i < MESSAGE_COUNT; ++i) {
                Message<String> message = Message.create(String.format("Hello World! [%s]", i)); 
9

                Tracker tracker = sender.send(message); 
10

                tracker.awaitSettlement(); 
11


                System.out.println(String.format("Sent message to %s: %s", sender.address(), message.body()));
            }
        }
    }
}

<.> 红帽构建的 Apache Qpid ProtonJ2 所需的软件包。

<.> 要发送的消息数量。

&lt ;.> server host 是 AMQP 连接的主机或虚拟主机的网络地址,可通过设置环境变量 HOST 来配置。

<.> serverPort 是代理接受连接的主机上的端口,可通过设置环境变量 PORT 来配置。

&lt ;.& gt; 客户端是可创建多个到代理的连接的容器。

<.& gt; 选项 用于各种设置,包括 UserPassword。请参阅 第 5.1 节 “连接选项” 了解更多信息。

<.& gt; 连接 是到代理的 AMQP 连接。

<.> 创建向代理传输消息的 发送者

在消息 send loop 中创建了新消息。

<.> 消息发送到代理。

<.> 等待代理设置消息。

运行示例

要运行示例程序,请参阅 第 3 章 开始使用

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部