4.2. 接收信息


此客户端程序使用 < connection-url > 连接到服务器,为源 <address& gt; 创建一个接收器,并接收信息直到终止或到达 < count> 信息。

示例:接收信息

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.Delivery;
import org.apache.qpid.protonj2.client.Message;
import org.apache.qpid.protonj2.client.Receiver; 
1


public class Receive {

    private static final int MESSAGE_COUNT = 100; 
2


    public static void main(String[] args) 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"); 
5


        final Client client = Client.create(); 
6


        final ConnectionOptions options = new ConnectionOptions(); 
7

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

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

             Receiver receiver = connection.openReceiver(address)) {  
9


            for (int i = 0; i < MESSAGE_COUNT; ++i) {
                Delivery delivery = receiver.receive(); 
10

                Message<String> message = delivery.message(); 
11


                System.out.println("Received message with body: " + message.body());
            }
        }
    }
}

1 1
红帽构建的 Apache Qpid ProtonJ2 所需的软件包。
2 2
要接收的消息数量。
3 3
server host 是 AMQP 连接的主机或虚拟主机的网络地址,可通过设置环境变量 HOST 来配置。
4 4
serverPort 是代理接受连接的主机上的端口,可通过设置环境变量 PORT 来配置。
5 5 6
客户端是可创建多个代理连接的容器。
6 7
选项 用于各种设置,包括 UserPassword。请参阅 第 5.1 节 “连接选项” 了解更多信息。
7 8
connection 是到代理的 AMQP 连接。
8 9
创建用于从代理接收消息 的接收器
9 10
在消息接收循环中,收到新的发送。
10 11
消息从 交付 中获取。

运行示例

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

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

Theme

© 2026 Red Hat
返回顶部