java 总线_通过 Java 使用 Azure 服务总线主题和订阅 (azure-messaging-servicebus) - Azure Service Bus | Microsoft Docs...

您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

向 Azure 服务总线主题发送消息,并从该主题的订阅接收消息 (Java)Send messages to an Azure Service Bus topic and receive messages from subscriptions to the topic (Java)

11/09/2020

本文内容

在本快速入门中,你将使用 azure-messaging-servicebus package 包编写 Java 代码,以将消息发送到 Azure 服务总线主题,然后从该主题的订阅接收消息。In this quickstart, you write Java code using the azure-messaging-servicebus package to send messages to an Azure Service Bus topic and then receive messages from subscriptions to that topic.

重要

本快速入门使用新的 azure-messaging-servicebus 包。This quickstart uses the new azure-messaging-servicebus package. 有关使用旧 azure-servicebus 包的快速入门,请参阅使用 azure-servicebus 发送和接收消息。For a quickstart that uses the old azure-servicebus package, see Send and receive messages using azure-servicebus.

先决条件Prerequisites

Azure 订阅。An Azure subscription. 若要完成本教程,需要一个 Azure 帐户。To complete this tutorial, you need an Azure account.

记下连接字符串、主题名称和订阅名称。Note down the connection string, topic name, and a subscription name. 本快速入门仅需使用一个订阅。You'll use only one subscription for this quickstart.

如果使用 Eclipse,则可安装 Azure Toolkit for Eclipse,其中包含用于 Java 的 Azure SDK。If you're using Eclipse, you can install the Azure Toolkit for Eclipse that includes the Azure SDK for Java. 然后,可将“适用于 Java 的 Microsoft Azure 库”添加到项目 。You can then add the Microsoft Azure Libraries for Java to your project.

将消息发送到主题Send messages to a topic

在本部分中,你将创建一个 Java 控制台项目,并添加代码以将消息发送到创建的主题。In this section, you'll create a Java console project, and add code to send messages to the topic you created.

创建 Java 控制台项目Create a Java console project

使用 Eclipse 或所选工具创建 Java 项目。Create a Java project using Eclipse or a tool of your choice.

配置应用程序以使用服务总线Configure your application to use Service Bus

添加对 Azure 服务总线库的引用。Add a reference to Azure Service Bus library. Maven 中心存储库中提供了服务总线的 Java 客户端库。The Java client library for Service Bus is available in the Maven Central Repository. 可使用 Maven 项目文件中的以下依赖项声明引用此库:You can reference this library using the following dependency declaration inside your Maven project file:

com.azure

azure-messaging-servicebus

7.0.0

添加将消息发送到主题的代码Add code to send messages to the topic

将以下 import 语句添加到 Java 文件的主题中。Add the following import statements at the topic of the Java file.

import com.azure.messaging.servicebus.*;

import com.azure.messaging.servicebus.models.*;

import java.util.concurrent.TimeUnit;

import java.util.function.Consumer;

import java.util.Arrays;

import java.util.List;

在类中,定义用于保存连接字符串和主题名称的变量,如下所示:In the class, define variables to hold connection string and topic name as shown below:

static String connectionString = "";

static String topicName = "";

static String subName = "";

将 替换为服务总线命名空间的连接字符串。Replace with the connection string to your Service Bus namespace. 并将 替换为主题名称。And, replace with the name of the topic.

在类中添加一个名为 sendMessage 的方法,以向主题发送一条消息。Add a method named sendMessage in the class to send one message to the topic.

static void sendMessage()

{

// create a Service Bus Sender client for the queue

ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()

.connectionString(connectionString)

.sender()

.topicName(topicName)

.buildClient();

// send one message to the topic

senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));

System.out.println("Sent a single message to the topic: " + topicName);

}

在类中添加一个名为 createMessages 的方法,以创建消息列表。Add a method named createMessages in the class to create a list of messages. 通常,可以从应用程序的不同部分获得这些消息。Typically, you get these messages from different parts of your application. 在这里,我们将创建一个示例消息列表。Here, we create a list of sample messages.

static List createMessages()

{

// create a list of messages and return it to the caller

ServiceBusMessage[] messages = {

new ServiceBusMessage("First message"),

new ServiceBusMessage("Second message"),

new ServiceBusMessage("Third message")

};

return Arrays.asList(messages);

}

添加一个名为 sendMessageBatch 方法的方法,以将消息发送到你创建的主题。Add a method named sendMessageBatch method to send messages to the topic you created. 此方法为主题创建 ServiceBusSenderClient,调用 createMessages 方法来获取消息列表,准备一个或多个批处理,并将批处理发送到主题。This method creates a ServiceBusSenderClient for the topic, invokes the createMessages method to get the list of messages, prepares one or more batches, and sends the batches to the topic.

static void sendMessageBatch()

{

// create a Service Bus Sender client for the topic

ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()

.connectionString(connectionString)

.sender()

.topicName(topicName)

.buildClient();

// Creates an ServiceBusMessageBatch where the ServiceBus.

ServiceBusMessageBatch messageBatch = senderClient.createMessageBatch();

// create a list of messages

List listOfMessages = createMessages();

// We try to add as many messages as a batch can fit based on the maximum size and send to Service Bus when

// the batch can hold no more messages. Create a new batch for next set of messages and repeat until all

// messages are sent.

for (ServiceBusMessage message : listOfMessages) {

if (messageBatch.tryAddMessage(message)) {

continue;

}

// The batch is full, so we create a new batch and send the batch.

senderClient.sendMessages(messageBatch);

System.out.println("Sent a batch of messages to the topic: " + topicName);

// create a new batch

messageBatch = senderClient.createMessageBatch();

// Add that message that we couldn't before.

if (!messageBatch.tryAddMessage(message)) {

System.err.printf("Message is too large for an empty batch. Skipping. Max size: %s.", messageBatch.getMaxSizeInBytes());

}

}

if (messageBatch.getCount() > 0) {

senderClient.sendMessages(messageBatch);

System.out.println("Sent a batch of messages to the topic: " + topicName);

}

//close the client

senderClient.close();

}

从订阅接收消息Receive messages from a subscription

在本部分中,你将添加代码以从主题的订阅中检索消息。In this section, you'll add code to retrieve messages from a subscription to the topic.

添加名为 receiveMessages 的方法,以从订阅检索消息。Add a method named receiveMessages to receive messages from the subscription. 此方法通过指定用于处理消息的处理程序和用于处理错误的另一个处理程序来为订阅创建 ServiceBusProcessorClient。This method creates a ServiceBusProcessorClient for the subscription by specifying a handler for processing messages and another one for handling errors. 然后,它将启动处理器,等待几秒钟,输出接收的消息,然后停止和关闭处理器。Then, it starts the processor, waits for few seconds, prints the messages that are received, and then stops and closes the processor.

// handles received messages

static void receiveMessages() throws InterruptedException

{

// Consumer that processes a single message received from Service Bus

Consumer messageProcessor = context -> {

ServiceBusReceivedMessage message = context.getMessage();

System.out.println("Received message: " + message.getBody().toString() + " from the subscription: " + subName);

};

// Consumer that handles any errors that occur when receiving messages

Consumer errorHandler = throwable -> {

System.out.println("Error when receiving messages: " + throwable.getMessage());

if (throwable instanceof ServiceBusReceiverException) {

ServiceBusReceiverException serviceBusReceiverException = (ServiceBusReceiverException) throwable;

System.out.println("Error source: " + serviceBusReceiverException.getErrorSource());

}

};

// Create an instance of the processor through the ServiceBusClientBuilder

ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder()

.connectionString(connectionString)

.processor()

.topicName(topicName)

.subscriptionName(subName)

.processMessage(messageProcessor)

.processError(errorHandler)

.buildProcessorClient();

System.out.println("Starting the processor");

processorClient.start();

TimeUnit.SECONDS.sleep(10);

System.out.println("Stopping and closing the processor");

processorClient.close();

}

更新 main 方法以调用 sendMessage、sendMessageBatch 和 receiveMessages 方法,并引发 InterruptedException。Update the main method to invoke sendMessage, sendMessageBatch, and receiveMessages methods and to throw InterruptedException.

public static void main(String[] args) throws InterruptedException {

sendMessage();

sendMessageBatch();

receiveMessages();

}

运行应用Run the app

运行程序,可以看到类似于以下输出的输出:Run the program to see the output similar to the following output:

Sent a batch of messages to the topic: mytopic

Starting the processor

Received message: First message from the subscription: mysub

Received message: Second message from the subscription: mysub

Received message: Third message from the subscription: mysub

Stopping and closing the processor

在 Azure 门户中的服务总线命名空间的“概述”页上,可看到传入和传出消息计数 。On the Overview page for the Service Bus namespace in the Azure portal, you can see incoming and outgoing message count. 可能需要等待一分钟左右,然后刷新页面才会看到最新值。You may need to wait for a minute or so and then refresh the page to see the latest values.

80809a2c1db5d731a94e7be42b9efda6.png

切换到窗格偏中下位置的“主题”选项卡,然后选择主题以查看该主题的“服务总线主题”页 。Switch to the Topics tab in the middle-bottom pane, and select the topic to see the Service Bus Topic page for your topic. 在此页上,“消息”图表中应显示四条传入消息和四条传出消息。On this page, you should see four incoming and four outgoing messages in the Messages chart.

5bfd90c3fa5f45a872933cad4cb98be9.png

如果注释掉 main 方法中的 receiveMessages 调用,并再次运行应用,则在“服务总线主题”页上,除 4 条传出消息外,还会看到 8 条传入消息(4 条新消息)。If you comment out the receiveMessages call in the main method and run the app again, on the Service Bus Topic page, you see 8 incoming messages (4 new) but four outgoing messages.

3d64fb8da1a0576389d26d24c92bfac0.png

在此页上,如果选择一个订阅,则将转到“服务总线订阅”页。On this page, if you select a subscription, you get to the Service Bus Subscription page. 可以在此页上查看活动消息计数、死信消息计数等。You can see the active message count, dead-letter message count, and more on this page. 在此示例中,还有四条活动消息未被接收器接收。In this example, there are four active messages that haven't been received by a receiver yet.

615053811e330c6d1df8dadc119c0454.png

后续步骤Next steps

请参阅以下文档和示例:See the following documentation and samples:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值