共用方式為


在 Spring 應用程式中使用 Azure 服務匯流排

本文說明如何在以 Spring Framework 建置的 Java 應用程式中使用 Azure 服務匯流排。

Azure 提供稱為 Azure 服務匯流排 (服務匯流排) 的異步傳訊平臺,其以進階消息佇列通訊協定 1.0 (AMQP 1.0) 標準為基礎。 您可以在支援的 Azure 平臺範圍內使用 服務匯流排。

Spring Cloud Azure 提供各種模組,可讓您使用 Spring 架構,將訊息傳送至 服務匯流排 佇列和主題/用帳戶,以及接收訊息。

您可以獨立使用下列模組,或針對不同的使用案例加以合併:

必要條件

注意

若要授與帳戶對 服務匯流排 資源的存取權,請在新建立的 Azure 服務匯流排 命名空間中,將 Azure 服務匯流排 數據傳送者和 Azure 服務匯流排 數據接收者角色指派給您目前使用的 Microsoft Entra 帳戶。 如需詳細資訊,請參閱使用 Azure 入口網站指派 Azure 角色

重要

需要 Spring Boot 2.5 版或更高版本,才能完成本教學課程中的步驟。

準備本機環境

在本教學課程中,設定和程式代碼沒有任何驗證作業。 不過,連線到 Azure 服務需要驗證。 若要完成驗證,您必須使用 Azure 身分識別用戶端連結庫。 Spring Cloud Azure 使用 DefaultAzureCredential,Azure 身分識別連結庫會提供它來協助您取得認證,而不需要變更任何程序代碼。

DefaultAzureCredential 支援多種驗證方法,並在執行階段判斷應使用的方法。 這種方法可讓您的應用程式在不同的環境中使用不同的驗證方法,例如本機或生產環境,而不需要實作環境特定的程序代碼。 如需詳細資訊,請參閱驗證 Azure 託管 Java 應用程式的 DefaultAzureCredential 一節。

若要使用 Azure CLI、IntelliJ 或其他方法來完成本機開發環境中的驗證,請參閱 Java 開發環境中的 Azure 驗證。 若要在 Azure 裝載環境中完成驗證,建議您使用受控識別。 如需詳細資訊,請參閱什麼是 Azure 資源受控識別?

注意

JMS API 的 Azure 服務匯流排 目前不支援 DefaultAzureCredential。 如果您使用 Spring JMS 搭配 服務匯流排,請忽略此步驟。

使用 Spring Cloud Azure 服務匯流排 入門版

Spring Cloud Azure 服務匯流排 Starter 模組會使用 Spring Boot 架構匯入 服務匯流排 Java 用戶端連結庫。 您可以在非互斥模式中使用 Spring Cloud Azure 和 Azure SDK。 因此,您可以在 Spring 應用程式中繼續使用 服務匯流排 Java 用戶端 API。

新增 服務匯流排 相依性

若要安裝 Spring Cloud Azure 服務匯流排 Starter 模組,請將下列相依性新增至您的pom.xml檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.13.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 服務匯流排 成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-servicebus</artifactId>
    </dependency>
    

撰寫應用程式以傳送和接收訊息的程序代碼

本指南會教導如何在 Spring 應用程式的內容中使用 服務匯流排 Java 用戶端。 我們在這裡介紹兩個替代方案。 建議的方法是使用 Spring Boot 自動設定,並使用 Spring 內容中的現用用戶端。 替代方式是以程序設計方式建置用戶端。

第一種方式涉及從 Spring IoC 容器自動連接用戶端豆類,相較於第二種方式,具有下列優點。 這些優點可讓您在使用 服務匯流排 客戶端進行開發時,更有彈性且更有效率的體驗。

  • 您可以使用 外部化組態 ,以便在不同的環境中使用相同的應用程式程序代碼。

  • 您可以將學習產生器模式的程式委派給 Spring Boot 架構,並將此用戶端註冊至應用程式內容。 此委派可讓您專注於如何將用戶端與您自己的商務需求搭配使用。

  • 您可以使用健康情況指標,輕鬆地檢查應用程式和內部元件的狀態和健康情況。

下列程式代碼範例示範如何使用 ServiceBusSenderClientServiceBusProcessorClient 搭配這兩個替代方案。

注意

適用於 服務匯流排 的 Azure Java SDK 提供多個用戶端來與 服務匯流排 互動。 入門版也會為所有 服務匯流排 客戶端和客戶端產生器提供自動設定。 我們在這裡只 ServiceBusSenderClient 使用 和 ServiceBusProcessorClient 作為範例。

使用 Spring Boot Autoconfiguration

若要將訊息傳送至 服務匯流排 並從 服務匯流排 接收訊息,請使用下列步驟設定應用程式:

  1. 設定您的 服務匯流排 命名空間和佇列,如下列範例所示:

    spring.cloud.azure.servicebus.namespace=<your-servicebus-namespace-name>
    spring.cloud.azure.servicebus.entity-name=<your-servicebus-queue-name>
    spring.cloud.azure.servicebus.entity-type=queue
    

    提示

    在這裡,我們使用 服務匯流排 佇列作為範例。 若要使用主題/訂用帳戶,您必須新增 屬性, spring.cloud.azure.servicebus.processor.subscription-name 並將值變更 entity-typetopic

  2. 建立新的 ServiceBusProcessorClientConfiguration Java 類別,如下列範例所示。 這個類別是用來註冊 的訊息和錯誤處理程式 ServiceBusProcessorClient

    @Configuration(proxyBeanMethods = false)
    public class ServiceBusProcessorClientConfiguration {
    
        @Bean
        ServiceBusRecordMessageListener processMessage() {
            return context -> {
                ServiceBusReceivedMessage message = context.getMessage();
                System.out.printf("Processing message. Id: %s, Sequence #: %s. Contents: %s%n", message.getMessageId(),
                        message.getSequenceNumber(), message.getBody());
            };
        }
    
        @Bean
        ServiceBusErrorHandler processError() {
            return context -> {
                System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n",
                        context.getFullyQualifiedNamespace(), context.getEntityPath());
            };
        }
    }
    
  3. ServiceBusSenderClient在 Spring 應用程式中插入 ,並呼叫相關的 API 來傳送訊息,如下列範例所示:

    @SpringBootApplication
    public class ServiceBusQueueApplication implements CommandLineRunner {
    
        private final ServiceBusSenderClient senderClient;
    
        public ServiceBusQueueApplication(ServiceBusSenderClient senderClient) {
            this.senderClient = senderClient;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceBusQueueApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            // send one message to the queue
            senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));
            System.out.printf("Sent a message to the queue");
            senderClient.close();
    
            // wait the processor client to consume messages
            TimeUnit.SECONDS.sleep(10);
        }
    
    }
    

    注意

    根據預設,自動連接 ServiceBusProcessorClient 豆的生命週期是由 Spring 內容所管理。 當 Spring 應用程式內容啟動時,處理器會自動啟動,並在 Spring 應用程式內容停止時停止。 若要停用此功能,請設定 spring.cloud.azure.servicebus.processor.auto-startup=false

  4. 啟動應用程式。 您會看到類似下列範例的記錄:

    Sent a message to the queue
    Processing message. Id: 6f405435200047069a3caf80893a80bc, Sequence #: 1. Contents: Hello, World!
    

以程式設計方式建置 服務匯流排 用戶端

您可以自行建置這些用戶端豆類,但程式很複雜。 在 Spring Boot 應用程式中,您必須管理屬性、了解產生器模式,以及向 Spring 應用程式內容註冊用戶端。 下列程式代碼範例示範如何執行此動作:

  1. 建立新的 ServiceBusClientConfiguration Java 類別,如下列範例所示。 這個類別是用來宣告 ServiceBusSenderClientServiceBusProcessorClient bean。

    @Configuration(proxyBeanMethods = false)
    public class ServiceBusClientConfiguration {
    
        private static final String SERVICE_BUS_FQDN = "<service-bus-fully-qualified-namespace>";
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @Bean
        ServiceBusClientBuilder serviceBusClientBuilder() {
            return new ServiceBusClientBuilder()
                       .fullyQualifiedNamespace(SERVICE_BUS_FQDN)
                       .credential(new DefaultAzureCredentialBuilder().build());
        }
    
        @Bean
        ServiceBusSenderClient serviceBusSenderClient(ServiceBusClientBuilder builder) {
            return builder
                   .sender()
                   .queueName(QUEUE_NAME)
                   .buildClient();
        }
    
        @Bean
        ServiceBusProcessorClient serviceBusProcessorClient(ServiceBusClientBuilder builder) {
            return builder.processor()
                          .queueName(QUEUE_NAME)
                          .processMessage(ServiceBusClientConfiguration::processMessage)
                          .processError(ServiceBusClientConfiguration::processError)
                          .buildProcessorClient();
        }
    
        private static void processMessage(ServiceBusReceivedMessageContext context) {
            ServiceBusReceivedMessage message = context.getMessage();
            System.out.printf("Processing message. Id: %s, Sequence #: %s. Contents: %s%n",
                message.getMessageId(), message.getSequenceNumber(), message.getBody());
        }
    
        private static void processError(ServiceBusErrorContext context) {
            System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n",
                    context.getFullyQualifiedNamespace(), context.getEntityPath());
        }
    }
    

    注意

    請務必將<service-bus-fully-qualified-namespace>佔位元取代為來自 Azure 入口網站 的 服務匯流排 主機名。 將<service-bus-queue-name>佔位元取代為您在 服務匯流排 命名空間中設定的您自己的佇列名稱。

  2. 將用戶端豆類插入您的應用程式,如下列範例所示:

    @SpringBootApplication
    public class ServiceBusQueueApplication implements CommandLineRunner {
    
        private final ServiceBusSenderClient senderClient;
    
        private final ServiceBusProcessorClient processorClient;
    
        public ServiceBusQueueApplication(ServiceBusSenderClient senderClient, ServiceBusProcessorClient processorClient) {
            this.senderClient = senderClient;
            this.processorClient = processorClient;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceBusQueueApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            // send one message to the queue
            senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));
            System.out.printf("Sent a message to the queue");
            senderClient.close();
    
            System.out.printf("Starting the processor");
            processorClient.start();
            TimeUnit.SECONDS.sleep(10);
            System.out.printf("Stopping and closing the processor");
            processorClient.close();
        }
    
    }
    
  3. 啟動應用程式。 您會看到類似下列範例的記錄:

    Sent a message to the queue
    Starting the processor
    ...
    Processing message. Id: 6f405435200047069a3caf80893a80bc, Sequence #: 1. Contents: Hello, World!
    Stopping and closing the processor
    

下列清單顯示此程式代碼沒有彈性或正常運作的原因:

  • 命名空間和佇列/主題/訂用帳戶名稱會硬式編碼。
  • 如果您使用 @Value 從 Spring 環境取得組態,則 application.properties 檔案中不能有 IDE 提示。
  • 如果您有微服務案例,則必須在每個專案中複製程序代碼,而且很容易犯錯,而且很難保持一致。

幸運的是,使用 Spring Cloud Azure 不需要自行建置用戶端豆類。 相反地,您可以直接插入豆類,並使用您已熟悉的設定屬性來設定 服務匯流排。

Spring Cloud Azure 也針對不同的案例提供下列全域設定。 如需詳細資訊,請參閱 Spring Cloud Azure 設定的 Azure 服務 SDK 全域設定一節。

  • Proxy 選項。
  • 重試選項。
  • AMQP 傳輸客戶端選項。

您也可以連線到不同的 Azure 雲端。 如需詳細資訊,請參閱 連線到不同的 Azure 雲端

使用 Spring Cloud Azure 服務匯流排 JMS 入門版

Spring Cloud Azure 服務匯流排 JMS 入門模組提供 Spring JMS 與 服務匯流排 整合。 下列影片說明如何使用 JMS 2.0 將 Spring JMS 應用程式與 Azure 服務匯流排 整合。


本指南說明如何使用適用於 JMS API 的 Spring Cloud Azure 服務匯流排 入門版,將訊息傳送至 服務匯流排 並從 服務匯流排 接收訊息。

新增 服務匯流排 相依性

若要安裝 Spring Cloud Azure 服務匯流排 JMS 入門模組,請將下列相依性新增至您的pom.xml檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.13.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 服務匯流排 JMS 成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-servicebus-jms</artifactId>
    </dependency>
    

撰寫應用程式以傳送和接收訊息的程序代碼

  1. 設定 服務匯流排 的 連接字串 和定價層,如下列範例所示:

    spring.jms.servicebus.connection-string=<service-bus-namespace-connection-string>
    spring.jms.servicebus.pricing-tier=<service-bus-pricing-tier>
    
  2. 建立訊息接收者。

    Spring 提供將訊息發佈至任何 POJO 的方法(純舊 Java 物件)。 首先,定義儲存和擷取使用者名稱的泛型 User 類別,如下列範例所示:

    public class User implements Serializable {
    
        private static final long serialVersionUID = -295422703255886286L;
    
        private String name;
    
        public User() {
        }
    
        public User(String name) {
            setName(name);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    提示

    Serializable 實作 以 send 在 Spring 架構中使用 JmsTemplate 方法。 否則,您應該定義自定義 MessageConverter 的 Bean,以文字格式將內容串行化為 JSON。 如需 的詳細資訊 MessageConverter,請參閱官方 Spring JMS 入門專案

  3. 您可以從這裡建立新的 QueueReceiveService Java 類別,如下列範例所示。 這個類別是用來定義訊息接收者。

    @Component
    public class QueueReceiveService {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @JmsListener(destination = QUEUE_NAME, containerFactory = "jmsListenerContainerFactory")
        public void receiveMessage(User user) {
            System.out.printf("Received a message from %s.", user.getName());
        }
    }
    

    注意

    請務必將 <service-bus-queue-name> 佔位元取代為您 服務匯流排 命名空間中設定的佇列名稱。

    如果您使用主題/訂用帳戶,請將 參數變更 destination 為主題名稱,且 containerFactory 應該是 topicJmsListenerContainerFactory。 此外,新增 subscription 參數來描述訂用帳戶名稱。

  4. 使用 Spring 連接傳送者和接收者來傳送和接收訊息,如下列範例所示:

    @SpringBootApplication
    @EnableJms
    public class ServiceBusJmsStarterApplication {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(ServiceBusJMSQueueApplication.class, args);
            JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    
            // Send a message with a POJO - the template reuse the message converter
            System.out.println("Sending a user message.");
            jmsTemplate.convertAndSend(QUEUE_NAME, new User("Tom"));
        }
    }
    

    注意

    請務必將<service-bus-queue-name>佔位元取代為您 服務匯流排 命名空間中設定的佇列名稱。

    提示

    請務必新增 @EnableIntegration 註釋,這會觸發以 @JmsListener標註的方法探索,並建立涵蓋下的訊息接聽程式容器。

  5. 啟動應用程式。 您會看到類似下列範例的記錄:

    Sending a user message.
    Received a message from Tom.
    

其他資訊

如需詳細資訊,請參閱如何搭配 服務匯流排 和AMQP 1.0使用 JMS API。

使用 Spring Messaging Azure 服務匯流排

Spring Messaging Azure 服務匯流排 模組支援具有 服務匯流排 的 Spring Messaging 架構。

如果您使用 Spring Messaging Azure 服務匯流排,則可以使用下列功能:

  • ServiceBusTemplate:以異步和同步方式將訊息傳送至 服務匯流排 佇列和主題。
  • @ServiceBusListener:將方法標示為目的地上 服務匯流排 訊息接聽程序的目標。

本指南說明如何使用 Spring Messaging Azure 服務匯流排,將訊息傳送至 服務匯流排 並從 服務匯流排 接收訊息。

新增 服務匯流排 相依性

若要安裝 Spring Messaging Azure 服務匯流排 模組,請將下列相依性新增至您的pom.xml檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.13.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Messaging 服務匯流排 和 Spring Cloud Azure 入門成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-messaging-azure-servicebus</artifactId>
    </dependency>
    

撰寫應用程式以傳送和接收訊息的程序代碼

  1. 設定 服務匯流排 的命名空間和佇列類型,如下列範例所示:

    spring.cloud.azure.servicebus.namespace=<service-bus-namespace-name>
    spring.cloud.azure.servicebus.entity-type=queue
    

    注意

    如果您使用主題/訂用帳戶,請將 spring.cloud.azure.servicebus.entity-type 值變更為 topic

  2. 建立新的 ConsumerService Java 類別,如下列範例所示。 這個類別是用來定義訊息接收者。

    @Service
    public class ConsumerService {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @ServiceBusListener(destination = QUEUE_NAME)
        public void handleMessageFromServiceBus(String message) {
            System.out.printf("Consume message: %s%n", message);
        }
    
    }
    

    注意

    如果您使用主題/訂用帳戶,請將的註釋參數變更為主題名稱,並新增 group 參數destination來描述訂用帳戶名稱。

  3. 使用 Spring 連接傳送者和接收者來傳送和接收訊息,如下列範例所示:

    @SpringBootApplication
    @EnableAzureMessaging
    public class Application {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        public static void main(String[] args) {
            ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class);
            ServiceBusTemplate serviceBusTemplate = applicationContext.getBean(ServiceBusTemplate.class);
            System.out.println("Sending a message to the queue.");
            serviceBusTemplate.sendAsync(QUEUE_NAME, MessageBuilder.withPayload("Hello world").build()).subscribe();
        }
    }
    

    提示

    請務必新增 @EnableAzureMessaging 註釋,這會觸發以 @ServiceBusListener標註的方法探索,並建立涵蓋下的訊息接聽程式容器。

  4. 啟動應用程式。 您會看到類似下列範例的記錄:

    Sending a message to the queue.
    Consume message: Hello world.
    

使用 Spring Integration Azure 服務匯流排

Spring Integration Azure 服務匯流排 模組支援 spring Integration 架構與 服務匯流排。

如果您的 Spring 應用程式使用 Spring Integration 訊息通道,您可以使用通道配接器在訊息通道之間路由傳送訊息,服務匯流排。

輸入通道配接器會將訊息從 服務匯流排 佇列或訂用帳戶轉送至訊息通道。 輸出通道配接器會將訊息從訊息通道發佈至 服務匯流排 佇列和主題。

本指南說明如何使用 Spring Integration Azure 服務匯流排,將訊息傳送至 服務匯流排 並從 服務匯流排 接收訊息。

新增 服務匯流排 相依性

若要安裝 Spring Cloud Azure 服務匯流排 Integration Starter 模組,請將下列相依性新增至您的 pom.xml 檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.13.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 服務匯流排 整合成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-integration-servicebus</artifactId>
    </dependency>
    

撰寫應用程式以傳送和接收訊息的程序代碼

  1. 設定 服務匯流排 的命名空間,如下列範例所示:

    spring.cloud.azure.servicebus.namespace=<your-servicebus-namespace-name>
    
  2. 建立新的 QueueReceiveConfiguration Java 類別,如下列範例所示。 這個類別是用來定義訊息接收者。

    @Configuration
    public class QueueReceiveConfiguration {
    
        private static final String INPUT_CHANNEL = "queue.input";
        private static final String QUEUE_NAME = "<your-servicebus-queue-name>";
        private static final String SERVICE_BUS_MESSAGE_LISTENER_CONTAINER = "queue-listener-container";
    
        /**
         * This message receiver binding with {@link ServiceBusInboundChannelAdapter}
         * via {@link MessageChannel} has name {@value INPUT_CHANNEL}
         */
        @ServiceActivator(inputChannel = INPUT_CHANNEL)
        public void messageReceiver(byte[] payload) {
            String message = new String(payload);
            System.out.printf("New message received: '%s'%n", message);
        }
    
        @Bean(SERVICE_BUS_MESSAGE_LISTENER_CONTAINER)
        public ServiceBusMessageListenerContainer messageListenerContainer(ServiceBusProcessorFactory processorFactory) {
            ServiceBusContainerProperties containerProperties = new ServiceBusContainerProperties();
            containerProperties.setEntityName(QUEUE_NAME);
            return new ServiceBusMessageListenerContainer(processorFactory, containerProperties);
        }
    
        @Bean
        public ServiceBusInboundChannelAdapter queueMessageChannelAdapter(
            @Qualifier(INPUT_CHANNEL) MessageChannel inputChannel,
            @Qualifier(SERVICE_BUS_MESSAGE_LISTENER_CONTAINER) ServiceBusMessageListenerContainer listenerContainer) {
            ServiceBusInboundChannelAdapter adapter = new ServiceBusInboundChannelAdapter(listenerContainer);
            adapter.setOutputChannel(inputChannel);
            return adapter;
        }
    
        @Bean(name = INPUT_CHANNEL)
        public MessageChannel input() {
            return new DirectChannel();
        }
    }
    
  3. 建立新的 QueueSendConfiguration Java 類別,如下列範例所示。 這個類別是用來定義訊息傳送者。

    @Configuration
    public class QueueSendConfiguration {
    
        private static final String OUTPUT_CHANNEL = "queue.output";
        private static final String QUEUE_NAME = "<your-servicebus-queue-name>";
    
        @Bean
        @ServiceActivator(inputChannel = OUTPUT_CHANNEL)
        public MessageHandler queueMessageSender(ServiceBusTemplate serviceBusTemplate) {
            serviceBusTemplate.setDefaultEntityType(ServiceBusEntityType.QUEUE);
            DefaultMessageHandler handler = new DefaultMessageHandler(QUEUE_NAME, serviceBusTemplate);
            handler.setSendCallback(new ListenableFutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                    System.out.println("Message was sent successfully.");
                }
    
                @Override
                public void onFailure(Throwable ex) {
                    System.out.println("There was an error sending the message.");
                }
            });
    
            return handler;
        }
    
        /**
         * Message gateway binding with {@link MessageHandler}
         * via {@link MessageChannel} has name {@value OUTPUT_CHANNEL}
         */
        @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL)
        public interface QueueOutboundGateway {
            void send(String text);
        }
    }
    
  4. 使用 Spring 連接傳送者和接收者來傳送和接收訊息,如下列範例所示:

    @SpringBootApplication
    @EnableIntegration
    @Configuration(proxyBeanMethods = false)
    public class ServiceBusIntegrationApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext applicationContext = SpringApplication.run(ServiceBusIntegrationApplication.class, args);
            QueueSendConfiguration.QueueOutboundGateway outboundGateway = applicationContext.getBean(QueueSendConfiguration.QueueOutboundGateway.class);
            System.out.println("Sending a message to the queue");
            outboundGateway.send("Hello World");
        }
    
    }
    

    提示

    請務必新增 @EnableIntegration 註釋,以啟用 Spring Integration 基礎結構。

  5. 啟動應用程式。 您會看到類似下列範例的記錄:

    Message was sent successfully.
    New message received: 'Hello World'
    

使用 Spring Cloud Stream 服務匯流排 Binder

若要在 Spring Cloud Stream 應用程式中呼叫 服務匯流排 API,請使用 Spring Cloud Azure 服務匯流排 Stream Binder 模組。

本指南說明如何使用 Spring Cloud Stream 服務匯流排 Binder 將訊息傳送至 服務匯流排 並從 服務匯流排 接收訊息。

新增 服務匯流排 相依性

若要安裝 Spring Cloud Azure 服務匯流排 Stream Binder 模組,請將下列相依性新增至您的pom.xml檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.13.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 服務匯流排 整合成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-stream-binder-servicebus</artifactId>
    </dependency>
    

撰寫應用程式以傳送和接收訊息的程序代碼

  1. 設定 服務匯流排 的命名空間,如下列範例所示:

    spring.cloud.azure.servicebus.namespace=<service-bus-namespace-name>
    
  2. 建立訊息接收者。

    若要使用您的應用程式作為事件接收,請指定下列資訊來設定輸入系結器:

    • Consumer宣告定義訊息處理邏輯的 Bean。 例如,下列 Consumer 豆子名為 consume

      @Bean
      public Consumer<Message<String>> consume() {
          return message -> {
              System.out.printf("New message received: '%s'.%n", message.getPayload());
          };
      }
      
    • 新增組態,以藉由取代<service-bus-queue-name>佔位符來指定queue取用的名稱,如下列範例所示:

      # name for the `Consumer` bean
      spring.cloud.function.definition=consume
      spring.cloud.stream.bindings.consume-in-0.destination=<service-bus-queue-name>
      

      注意

      若要從 服務匯流排 訂閱取用,請務必變更系consume-in-0結屬性,如下列範例所示:

      spring.cloud.stream.bindings.consume-in-0.destination=<service-bus-topic-name>
      spring.cloud.stream.bindings.consume-in-0.group=<service-bus-subscription-name>
      
  3. 建立訊息寄件者。

    若要使用您的應用程式作為事件來源,請指定下列資訊來設定輸出系結器:

    • Supplier定義 Bean,定義訊息來自應用程式內的位置。

      @Bean
      return () -> {
              System.out.println("Sending a message.");
              return MessageBuilder.withPayload("Hello world").build();
          };
      }
      
    • 新增組態以指定 queue 傳送的名稱,方法是取代 <your-servicebus-queue-name> 下列範例中的佔位元:

      # "consume" is added from the previous step
      spring.cloud.function.definition=consume;supply
      spring.cloud.stream.bindings.supply-out-0.destination=<your-servicebus-queue-name>
      spring.cloud.stream.servicebus.bindings.supply-out-0.producer.entity-type=queue
      

      注意

      若要傳送至 服務匯流排 主題,請務必將 變更entity-typetopic

  4. 啟動應用程式。 您會看到類似下列範例的記錄:

    Sending a message.
    New message received: 'Hello world'.
    

部署至 Azure Spring Apps

現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring Apps 可讓您輕鬆地將 Spring Boot 應用程式部署至 Azure,而不需要變更任何程式代碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員可以專注於處理程式碼。 Azure Spring 應用程式提供生命週期管理,使用全方位的監視和診斷、組態管理、服務探索、持續整合與持續傳遞的整合、藍綠部署等等。 若要將應用程式部署至 Azure Spring Apps,請參閱 將第一個應用程式部署至 Azure Spring Apps

下一步

另請參閱

如需更多適用於 azure Microsoft Spring Boot Starters 的詳細資訊,請參閱 什麼是 Spring Cloud Azure?