(Azure Service Bus服务总线的两大类消息处理方式: 队列Queue和主题Topic)

 

问题描述

使用Service Bus作为企业消息代理,当有大量的数据堆积再Queue或Topic中时,如何来优化接收端处理消息的能力呢?

详细解释

在接收端(Receover)的代码中,有两个属性与处理消息的能力有关。一是maxConcurrentCalls(最大并发处理数), 二是prefetchCount (预提取消息数)。 在Service Bus的SDK(azure-messaging-servicebus:7.0.0.0)中,他们的描述如下:

maxConcurrentCalls
接收端所定义的ServiceBusProcessorClient处理的最大并发消息数。

The max concurrent messages that should be processed by the processor.

package com.azure.messaging.servicebus.implementation.models;
... ...
public final class ServiceBusProcessorClientOptions {

... ...
/** * The max concurrent messages that should be processed by the processor. * @return The max concurrent message that should be processed by the processor. */ public int getMaxConcurrentCalls() { return maxConcurrentCalls; } /** * Sets the max concurrent messages that can be processed by the processor. If not set, the default value will be 1. * * @param maxConcurrentCalls The max concurrent messages that can be processed by the processor. * @return The updated instance of {@link ServiceBusProcessorClientOptions}. */ public ServiceBusProcessorClientOptions setMaxConcurrentCalls(int maxConcurrentCalls) { this.maxConcurrentCalls = maxConcurrentCalls; return this; }
prefetchCount

接收端要预先提取的消息数

The number of messages to prefetch

package com.azure.messaging.servicebus;
... ...

public final class ServiceBusClientBuilder { 
... ...

// Using 0 pre-fetch count for both receive modes, to avoid message lock lost exceptions in application 
// receiving messages at a slow rate. Applications can set it to a higher value if they need better performance. 
private static final int DEFAULT_PREFETCH_COUNT = 1;


    /**
     * Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
     * messages from Service Bus.
     *
     * @see ServiceBusReceiverAsyncClient
     * @see ServiceBusReceiverClient
     */
    @ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
    public final class ServiceBusReceiverClientBuilder {
        private boolean enableAutoComplete = true;
        private int prefetchCount = DEFAULT_PREFETCH_COUNT;
        private String queueName;
        private SubQueue subQueue;
        private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK;
        private String subscriptionName;
        private String topicName;
        private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;

        private ServiceBusReceiverClientBuilder() {
        }

 

在初始化ServiceBusProcessorClient对象时,可以设置maxConcurrentCalls和prefetchCount的值。如

        int concall=5;
        int prefetch =10;
        // Create an instance of the processor through the ServiceBusClientBuilder
        ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder().connectionString(connectionString)
                .processor().topicName(topicName).subscriptionName(subName).processMessage(messageProcessor)
                .processError(errorHandler).maxConcurrentCalls(concall).prefetchCount(prefetch).buildProcessorClient();

System.out.println(
"Starting the processor"); System.out.println("Set Processor: maxConcurrentCalls = "+concall+", prefetchCount = "+prefetch);

 

实验验证

在本次的实验中,如何来验证maxConcurrentCalls值启作用了呢?如何判断prefetchCount是否获取了消息呢? 

  • 针对maxConcurrentCalls,可以在处理消息的代码中[processMessage(messageProcessor)]打印出当前线程的ID[Thread.currentThread().getId()]。
  • 针对prefetchCount,可以从侧面来验证,即获取message的DeliveryCount来判断已经预提取了多少次

本次实验的代码参考Azure Service Bus的快速入门文档所编写,文末包含全部的代码和POM.XML文件。 从订阅接收消息https://docs.azure.cn/zh-cn/service-bus-messaging/service-bus-java-how-to-use-topics-subscriptions#receive-messages-from-a-subscription

首先在代码中设置concall和prefetch值。默认情况下为1.本次实验也从1开始,在设定的10秒钟之内查看消费消息的数量。

        int concall=1;
        int prefetch =1;
        // Create an instance of the processor through the ServiceBusClientBuilder
        ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder().connectionString(connectionString)
                .processor().topicName(topicName).subscriptionName(subName).processMessage(messageProcessor)
                .processError(errorHandler).maxConcurrentCalls(concall).prefetchCount(prefetch).buildProcessorClient();
                System.out.println("Starting the processor");
        System.out.println("Set Processor: maxConcurrentCalls = "+concall+", prefetchCount = "+prefetch);
        
        processorClient.start();

然后再处理消息的对象中,打印出当前处理消息的次序,消息ID,Delivery次数,处理消息的线程ID。

        Consumer<ServiceBusReceivedMessageContext> messageProcessor = context -> {
            ServiceBusReceivedMessage message = context.getMessage();

            ordernumber++;

            System.out.println(ordernumber + " Message ID:" + message.getMessageId() + ",Current Delivery Count:"
                    + message.getDeliveryCount() + ",Current Thread ID:" + Thread.currentThread().getId());
        };

第一次实验:处理消息的线程号只有一个:21, 在10秒时间中处理23条消息

Hello World!
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting the processor
Set Processor: maxConcurrentCalls = 1, prefetchCount = 1
1 Message ID:7caf842c-b98e-4bb5-88e6-bbacc8c45044,Current Delivery Count:1,Current Thread ID:21
2 Message ID:0589aa12-9787-46dd-ba80-412cb125abee,Current Delivery Count:1,Current Thread ID:21
3 Message ID:86d891cf-f3fc-42d9-88ba-bb90bf410f53,Current Delivery Count:1,Current Thread ID:21
4 Message ID:df22f493-968d-4ab6-a8f8-73758d365079,Current Delivery Count:1,Current Thread ID:21
5 Message ID:17078967-3612-44f4-8225-bad30a988a92,Current Delivery Count:1,Current Thread ID:21
6 Message ID:f0a21a08-9a31-4a06-be72-546bbe623e55,Current Delivery Count:1,Current Thread ID:21
7 Message ID:da0234a5-0b7b-486a-bc48-d10cc8729bea,Current Delivery Count:1,Current Thread ID:21
8 Message ID:4ea180f4-c1a0-4bca-9364-a573487451ee,Current Delivery Count:1,Current Thread ID:21
9 Message ID:dca04404-da54-49b2-88c1-18c08937b3d1,Current Delivery Count:1,Current Thread ID:21
10 Message ID:dcba46a2-396a-4915-8019-38a8c04c9555,Current Delivery Count:1,Current Thread ID:21
11 Message ID:deb2874d-9b24-4eef-9978-8e0f83cee9ff,Current Delivery Count:1,Current Thread ID:21
12 Message ID:8324baf3-086d-4e05-988d-c7c38178c3f6,Current Delivery Count:1,Current Thread ID:21
13 Message ID:053062ed-f7e7-431f-8dc8-45a257ef1bc7,Current Delivery Count:1,Current Thread ID:21
14 Message ID:f7e727a5-179f-415a-9491-c18a17eee703,Current Delivery Count:1,Current Thread ID:21
15 Message ID:6bd411ea-4fa3-4cfa-ab81-5ced59ef38f8,Current Delivery Count:1,Current Thread ID:21
16 Message ID:61508dc1-8636-4367-9a4c-9ab02a93f6e9,Current Delivery Count:1,Current Thread ID:21
17 Message ID:832b15c9-ed19-4573-b1c4-cd531aa59791,Current Delivery Count:1,Current Thread ID:21
18 Message ID:a8bb8702-2c9b-4a4c-a58f-6a8596f3ba8a,Current Delivery Count:1,Current Thread ID:21
19 Message ID:e19a6f09-d56a-48c8-b1b9-71fc4ba4e89c,Current Delivery Count:1,Current Thread ID:21
20 Message ID:1feefd63-5fd7-4a27-b008-c224d34f8e0f,Current Delivery Count:1,Current Thread ID:21
21 Message ID:3f3e0048-aa82-4937-9019-89e7e67bd4a4,Current Delivery Count:1,Current Thread ID:21
22 Message ID:da7a5b24-ff7b-4a86-a79c-2b563ab676c5,Current Delivery Count:1,Current Thread ID:21
23 Message ID:4422744a-1fb3-4a5c-a0e8-7b598624de56,Current Delivery Count:1,Current Thread ID:21
Total Process Message Count = 23 in 10 seconds.
Stopping and closing the processor
Done World!

 

第二次实验处理消息的线程号有5个:21,21,23,24,25, 在10秒时间中处理42条消息

Hello World!
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting the processor
Set Processor: maxConcurrentCalls = 5, prefetchCount = 10
1 Message ID:71333a8b-82a6-48a6-b313-dd5daf155878,Current Delivery Count:0,Current Thread ID:21
2 Message ID:7349bd87-d52e-462e-b549-0069845a89ae,Current Delivery Count:0,Current Thread ID:22
3 Message ID:6b1ae777-b798-42f1-b9c8-85fe09be2f06,Current Delivery Count:0,Current Thread ID:23
4 Message ID:9fb1a641-a9b2-49b6-a352-da8d7ed77894,Current Delivery Count:0,Current Thread ID:24
5 Message ID:7e27a824-577d-4407-8ec2-2813b426ee49,Current Delivery Count:0,Current Thread ID:25
6 Message ID:24fd3b47-1619-4570-9ccb-55731f5c94a3,Current Delivery Count:0,Current Thread ID:21
7 Message ID:686709bb-9642-482b-9693-58a130229149,Current Delivery Count:0,Current Thread ID:22
8 Message ID:de9ee204-1a16-4c5a-8d8a-eb2c49c79f99,Current Delivery Count:0,Current Thread ID:23
9 Message ID:bdda51bc-53a9-4df4-8965-ee94a28c10ac,Current Delivery Count:0,Current Thread ID:24
10 Message ID:6a3125af-ca7a-4a2e-99be-45b74421e26c,Current Delivery Count:0,Current Thread ID:25
11 Message ID:51bc3166-bd95-44e2-b61c-655f3711f2b9,Current Delivery Count:0,Current Thread ID:21
12 Message ID:bf5fb817-361f-4089-9732-6da915b98d41,Current Delivery Count:0,Current Thread ID:22
13 Message ID:3f61c3e0-f331-4501-8df7-00b0a612edd6,Current Delivery Count:0,Current Thread ID:23
14 Message ID:f15ebb11-8551-4ede-b0af-98834a7dfe40,Current Delivery Count:0,Current Thread ID:24
15 Message ID:033076bf-96b8-44b5-8682-a0c61e19dd9a,Current Delivery Count:0,Current Thread ID:25
16 Message ID:0f3a8314-269a-407f-a3fe-b0ed2b0f2a42,Current Delivery Count:0,Current Thread ID:21
17 Message ID:46f8568a-b9cc-482d-81f3-b79cb12c52f4,Current Delivery Count:0,Current Thread ID:22
18 Message ID:10704772-8868-4617-8d7b-2fe66d1b017b,Current Delivery Count:0,Current Thread ID:23
19 Message ID:b741efcb-8a54-436c-90cc-e92e43de25e6,Current Delivery Count:0,Current Thread ID:24
20 Message ID:11dba5e4-7075-4331-8b88-e28378fe6aa8,Current Delivery Count:0,Current Thread ID:25
21 Message ID:92d59ff0-5601-4168-b9ae-b7a7762442d9,Current Delivery Count:0,Current Thread ID:21
22 Message ID:8ee7da87-2e52-48fb-a779-886e8c5dc87e,Current Delivery Count:0,Current Thread ID:22
23 Message ID:1251b86a-ec81-4d73-a739-143556a42bc6,Current Delivery Count:0,Current Thread ID:23
24 Message ID:ea5da6fc-f826-4553-941a-1073212becd9,Current Delivery Count:0,Current Thread ID:24
25 Message ID:00c583af-b818-4780-ba0f-050d6d80456d,Current Delivery Count:0,Current Thread ID:25
26 Message ID:c386599f-8da2-4a2d-89b2-013725344e5e,Current Delivery Count:0,Current Thread ID:21
27 Message ID:151330aa-44df-4cc6-9137-c1b069eeb230,Current Delivery Count:0,Current Thread ID:22
28 Message ID:4cd13836-f9e2-488a-9636-d1c0c26a8f83,Current Delivery Count:0,Current Thread ID:23
29 Message ID:920f3ab0-a836-44be-9621-62e388ef2421,Current Delivery Count:0,Current Thread ID:24
30 Message ID:e5eba8ed-b26f-4460-a8ef-818397801648,Current Delivery Count:0,Current Thread ID:25
31 Message ID:a70faece-03f5-43c3-b70d-ac5bae3c5b2f,Current Delivery Count:0,Current Thread ID:21
32 Message ID:cb341aea-eb84-4a5d-ab11-1fbe7c82a984,Current Delivery Count:0,Current Thread ID:22
33 Message ID:160405e9-485f-4fab-b11a-a7dd71afc0d0,Current Delivery Count:0,Current Thread ID:23
34 Message ID:4494f35a-ca3a-4e3e-9604-4a556b0a36a0,Current Delivery Count:0,Current Thread ID:24
35 Message ID:704503fa-44a9-4bb5-ac7d-27e52037eed8,Current Delivery Count:0,Current Thread ID:25
36 Message ID:e847014f-2721-4d28-a3e2-33eb2fc4c6cf,Current Delivery Count:0,Current Thread ID:21
37 Message ID:5ded8f94-7cd7-4679-9aca-cd1b67082174,Current Delivery Count:0,Current Thread ID:22
38 Message ID:ae6c6f73-30d6-4a0a-a104-2fcf1a709e57,Current Delivery Count:0,Current Thread ID:23
39 Message ID:5b5a6b32-a9aa-493c-ad3d-c88dc8a15ae4,Current Delivery Count:0,Current Thread ID:24
40 Message ID:1510b7fe-744e-4647-a373-4434e1e1b470,Current Delivery Count:0,Current Thread ID:25
41 Message ID:9a64f921-015d-4372-b1e9-3475c4570597,Current Delivery Count:0,Current Thread ID:21
42 Message ID:b744cc37-f3a4-41ed-9582-2bfdf4dc759c,Current Delivery Count:0,Current Thread ID:22
Total Process Message Count = 42 in 10 seconds.
Stopping and closing the processor
Done World!

 

第三次实验处理消息的线程号有10个:21,21 … 30, 在10秒时间中处理46条消息

Hello World!
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting the processor
Set Processor: maxConcurrentCalls = 10, prefetchCount = 30
1 Message ID:a07fe5a5-047d-4d25-ad1e-c199ef13b249,Current Delivery Count:1,Current Thread ID:21
2 Message ID:d8a45441-d365-4c71-8483-3b1e2714b1bd,Current Delivery Count:1,Current Thread ID:22
3 Message ID:819512bd-6b45-48dd-8ccf-4f81dc45423a,Current Delivery Count:1,Current Thread ID:23
4 Message ID:0390edb1-6f72-41b5-a81a-b1ff08b257b4,Current Delivery Count:1,Current Thread ID:24
5 Message ID:f36cd0ff-84b4-4bd5-938b-83ba94f857f1,Current Delivery Count:1,Current Thread ID:25
6 Message ID:a9155e92-d1a6-4f42-876d-3b18222c9e09,Current Delivery Count:1,Current Thread ID:26
7 Message ID:d0d6d5b8-8ec1-40f2-aee9-c2273ea8dc0a,Current Delivery Count:1,Current Thread ID:27
8 Message ID:c5d9b0c6-bb40-4004-864f-1c5b0f3b66fc,Current Delivery Count:1,Current Thread ID:28
9 Message ID:a0510766-3651-49bb-9b49-fde39ad721dc,Current Delivery Count:1,Current Thread ID:29
10 Message ID:9114cd88-e3ea-4e29-9ba3-45d162d60e14,Current Delivery Count:1,Current Thread ID:30
11 Message ID:d9634704-6808-46b1-959c-fffd77507818,Current Delivery Count:1,Current Thread ID:21
12 Message ID:7f6a9d7e-d176-4841-86c5-c0562aad7df3,Current Delivery Count:1,Current Thread ID:22
13 Message ID:16a87277-2f6c-4a71-bb8e-3d33fac588ff,Current Delivery Count:1,Current Thread ID:23
14 Message ID:399ed46c-3434-41b3-9e3a-6149fe1b1902,Current Delivery Count:1,Current Thread ID:24
15 Message ID:718dadd1-abe4-49fc-bb72-f300aedf99d4,Current Delivery Count:1,Current Thread ID:25
16 Message ID:01ae727a-c863-4039-abac-52a9a80b0506,Current Delivery Count:1,Current Thread ID:26
17 Message ID:31a68d59-6ed0-4ac8-b76a-cceb6ffe73c6,Current Delivery Count:1,Current Thread ID:27
18 Message ID:e40fbb11-0781-44b0-ab50-304f8fbfcb5f,Current Delivery Count:1,Current Thread ID:28
19 Message ID:99073a2a-6219-4c4f-9ebf-fb2072efcf05,Current Delivery Count:1,Current Thread ID:29
20 Message ID:5c796c6d-50c2-4602-b0e2-3e2d50caabf6,Current Delivery Count:1,Current Thread ID:30
21 Message ID:2ddd712c-a719-4aef-9be3-0a4648b68a55,Current Delivery Count:1,Current Thread ID:21
22 Message ID:b093177d-184a-4408-bd26-c0acfe104b2f,Current Delivery Count:1,Current Thread ID:22
23 Message ID:9a08e547-f31b-42f2-a01b-6b7becf794ed,Current Delivery Count:1,Current Thread ID:23
24 Message ID:d03308e2-9fba-4516-aa79-e9062af77745,Current Delivery Count:1,Current Thread ID:24
25 Message ID:96b36c50-1dfd-495c-b4a0-646abc48b928,Current Delivery Count:1,Current Thread ID:25
26 Message ID:3e675da1-de66-4edc-a497-860e79740ca8,Current Delivery Count:1,Current Thread ID:26
27 Message ID:0b23ed25-9a41-450a-ac95-01156b0eae8b,Current Delivery Count:1,Current Thread ID:27
28 Message ID:bc252a89-2501-43aa-b216-0f23511ce82a,Current Delivery Count:1,Current Thread ID:28
29 Message ID:66342a7d-eff6-4df4-b951-5094add40edb,Current Delivery Count:1,Current Thread ID:29
30 Message ID:f60eebba-6808-4d33-b669-b8b43fad8a0d,Current Delivery Count:1,Current Thread ID:30
31 Message ID:e7f0b9be-9f19-4ddb-98b0-1b000808a281,Current Delivery Count:1,Current Thread ID:21
32 Message ID:0d94f324-9b1f-4583-a70f-aa6a1d5e54ec,Current Delivery Count:1,Current Thread ID:22
33 Message ID:707442b9-cdec-4ba2-a3e1-1ae916356915,Current Delivery Count:1,Current Thread ID:23
34 Message ID:ae117b5b-dea0-4a87-a38d-b1deb801b6a6,Current Delivery Count:1,Current Thread ID:24
35 Message ID:12eda7a1-ec8b-47a4-9e6e-33bc494610b5,Current Delivery Count:1,Current Thread ID:25
36 Message ID:c4f9b7ac-d363-4488-89ff-fa95d862c49b,Current Delivery Count:1,Current Thread ID:26
37 Message ID:e68f136e-a731-4de2-aea7-ada21772bc6d,Current Delivery Count:1,Current Thread ID:27
38 Message ID:d6d60cb4-57ef-40da-a1ae-7f8a808566ab,Current Delivery Count:1,Current Thread ID:28
39 Message ID:f779e166-cc90-4880-b1a3-4b413088f469,Current Delivery Count:1,Current Thread ID:29
40 Message ID:68f6711c-a534-46ed-a68d-4441722a6ffa,Current Delivery Count:1,Current Thread ID:30
41 Message ID:f197dacb-cf35-4cad-9e89-6a6f7c9b0236,Current Delivery Count:1,Current Thread ID:21
42 Message ID:8519277f-7f37-407d-9736-580b144bec81,Current Delivery Count:1,Current Thread ID:22
43 Message ID:e1b67b72-ec44-4f94-84b2-3ced2fcff598,Current Delivery Count:1,Current Thread ID:23
44 Message ID:d369226c-1ebd-4505-bb85-74d458c54f37,Current Delivery Count:1,Current Thread ID:24
45 Message ID:66a45a5b-22f9-4758-b793-ae92841faedb,Current Delivery Count:1,Current Thread ID:25
46 Message ID:8f027132-6b66-41fe-ad14-d6e7c437fb38,Current Delivery Count:1,Current Thread ID:26
Total Process Message Count = 46 in 10 seconds.
Stopping and closing the processor
Done World!

三次测试的结论

在测试中,由于测试的时长只有10秒,所以无法得出一个合理的maxConcurrentCalls和prefetchCount值。至少maxCouncurrentCalls的值能大幅度提升接收端(Receiver)处理消息的能力。在第三次的的测试中,我们发现Delivery Count的计数变为了1,这是因为在第二次测试中,我们设置的预提取数量为10,每次提取的数量大于了接收端能处理的数量。在10秒钟的测试中,并没有完全处理完所有提取出来的消息,以致于在第三次测试中,这些消息的Delivery次数从0变成了1。

 

优化建议

预提取可加快消息流程,方法是在应用程序请求消息时及请求消息前,准备好消息用于本地检索。

  • 通过 ReceiveAndDelete 接收模式,预提取缓存区获取的所有消息在队列中不再可用,仅保留在内存中预提取缓存区,直到应用程序通过 Receive/ReceiveAsync 或 OnMessage/OnMessageAsync API 接收到它们 。 如果在应用程序接收到消息前终止应用程序,这些消息将丢失,且不可恢复

 

  • 在 PeekLock 接收模式下,提取到预提取缓存区的消息将以锁定状态进入缓存区,并且将超时时钟用于锁定计时。 如果预提取缓存区很大,且处理所需时间过长,以致消息锁定在驻留于预提取缓存区,甚至应用程序还在处理消息时就到期,可能出现一些令人困惑的事件要应用程序处理

 

如果消息处理需要高度的可靠性,且处理需要大量精力和时间,则建议谨慎使用或者丝毫不用预提取功能。

如果需要较高吞吐量且消息处理通常比较便宜,则预提取会产生显著的吞吐量优势。

需要均衡对队列或订阅配置的最大预提取数和锁定持续时间,以便锁定超时至少超出最大预提取缓存区大小外加一条消息的累积预期消息处理时间。 同时,锁定超时不应过长,防止消息在被意外丢弃后超出其最大 TimeToLive,因此需要消息的锁定在重新传送消息前到期。

 

附录一:使用Service Bus Explorer工具快速生成大量消息

 

附录二:测试实例pom.xml内容

 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>testgroupid</groupId>
  <artifactId>testartifactid</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>testartifactid</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-messaging-servicebus</artifactId>
      <version>7.0.0</version>
  </dependency>
  
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-messaging-servicebus</artifactId>
      <version>7.0.0-beta.7</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

附录三:App.java代码

package com.servicebus.test;

import com.azure.messaging.servicebus.*;
import com.azure.messaging.servicebus.models.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App {

    static String connectionString = "Endpoint=sb://xxxxxxxx.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    static String topicName = "thisistest";
    static String subName = "lubusb1";

    static int ordernumber = 0;

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Hello World!");

        // sendMessage();
        // sendMessageBatch();

        receiveMessages();

        System.out.println("Done World!");
    }

    // handles received messages
    static void receiveMessages() throws InterruptedException {
        // Consumer that processes a single message received from Service Bus
        Consumer<ServiceBusReceivedMessageContext> messageProcessor = context -> {
            ServiceBusReceivedMessage message = context.getMessage();

            ordernumber++;

            System.out.println(ordernumber + " Message ID:" + message.getMessageId() + ",Current Delivery Count:"
                    + message.getDeliveryCount() + ",Current Thread ID:" + Thread.currentThread().getId());
        };

        // Consumer that handles any errors that occur when receiving messages
        Consumer<Throwable> 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());
            }
        };

        int concall=10;
        int prefetch =30;
        // Create an instance of the processor through the ServiceBusClientBuilder
        ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder().connectionString(connectionString)
                .processor().topicName(topicName).subscriptionName(subName).processMessage(messageProcessor)
                .processError(errorHandler).maxConcurrentCalls(concall).prefetchCount(prefetch).buildProcessorClient();
                System.out.println("Starting the processor");
        System.out.println("Set Processor: maxConcurrentCalls = "+concall+", prefetchCount = "+prefetch);
        
        processorClient.start();
               

        TimeUnit.SECONDS.sleep(10);
        System.out.println("Total Process Message Count = "+ordernumber+" in 10 seconds.");
        System.out.println("Stopping and closing the processor");
        processorClient.close();
    }

    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);
    }

    static List<ServiceBusMessage> 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);
    }

    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<ServiceBusMessage> 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();
    }
}

 

参考资料

Service Bus Explorer:https://github.com/paolosalvatori/ServiceBusExplorer

预提取 Azure 服务总线消息:https://docs.azure.cn/zh-cn/service-bus-messaging/service-bus-prefetch#if-it-is-faster-why-is-prefetch-not-the-default-option

预提取:https://docs.azure.cn/zh-cn/service-bus-messaging/service-bus-performance-improvements?tabs=net-standard-sdk-2#prefetching

向 Azure 服务总线队列发送消息并从中接收消息 (Java):https://docs.azure.cn/zh-cn/service-bus-messaging/service-bus-java-how-to-use-queues

 

版权声明:本文为lulight原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lulight/p/14545796.html