本文示範如何在使用 Spring Framework 所建置的Java應用程式中使用 Azure 儲存體 Queue。
Azure 儲存體 Queue 實作雲端佇列,以促進分散式應用程式元件間的通訊。 每個佇列都會維護一份可由傳送端元件新增、且可由接收端元件處理的訊息清單。 透過佇列,您的應用程式將可立即進行調整以因應需求。
Spring Cloud Azure 提供多種模組,讓 Spring 框架能傳送訊息到Azure 儲存體 Queues,並接收訊息。 您可以獨立使用這些模組,或針對不同的使用案例加以結合,如下列清單所述:
Spring Cloud Azure 儲存體 Queue Starter 允許你使用 Storage Queues Java SDK 客戶端庫,搭配 Spring Boot 功能,發送和接收訊息。
Spring Messaging Azure 儲存體 Queue 讓你透過Spring Messaging API 與儲存佇列互動。 Spring Integration Azure 儲存體 Queue 讓你能將 Spring Integration Message Channels 與儲存隊列連結起來。
必要條件
Azure訂閱 - 免費創建。
Java 開發套件(JDK),版本 8 或更高。
一個 Azure 儲存帳戶和 Azure 佇列。 如果您沒有這些資源,請先建立記憶體帳戶,然後建立佇列。 更多資訊請參閱 建立儲存帳戶 以及 快速入門:建立佇列並透過 Azure portal 新增訊息的 建立佇列章節。
Spring Boot 應用程式。 如果您沒有這個應用程式,請使用 Spring Initializr 來建立 Maven 專案。 請務必選擇 Maven Project,並在 Dependencies 中新增 Spring Web 相依,然後選擇 Java 版本 8 或更高版本。
注意
要授權你的帳號存取資源,在你新建立的Azure 儲存體帳號中,將 Storage Queue Data Contributor 角色指派給你目前使用的Microsoft Entra帳號。 欲了解更多資訊,請參閱 使用 Azure 入口網站指派 Azure 角色。
重要
需要 Spring Boot 2.5 版或更高版本,才能完成本教學課程中的步驟。
準備本地環境
在本教學課程中,設定和程式代碼沒有任何驗證作業。 然而,連接 Azure 服務需要驗證。 要完成驗證,你需要使用 Azure Identity 用戶端函式庫。 Spring Cloud Azure 使用 DefaultAzureCredential,這是 Azure Identity 函式庫提供的,幫助你在不更改程式碼的情況下取得憑證。
DefaultAzureCredential 支援多種驗證方法,並在執行階段判斷應使用的方法。 這種方法可讓您的應用程式在不同的環境中使用不同的驗證方法,例如本機或生產環境,而不需要實作環境特定的程序代碼。 欲了解更多資訊,請參閱 Authenticate Azure-hosted Java applications 的 DefaultAzureCredential 章節。
若要使用 Azure CLI、IntelliJ 或其他方法在本地開發環境中完成認證,請參見 Azure Java開發環境中的認證。 在 Azure 主機環境中完成認證時,我們建議使用管理身份。 欲了解更多資訊,請參閱 Azure資源的受管理身份是什麼?
使用 Spring Cloud Azure 儲存佇列啟動器
Spring Cloud Azure 儲存體 Queue Starter 模組透過 Spring Boot 框架匯入 Azure 儲存體 Java 的佇列用戶端函式庫。 你可以同時使用 Spring Cloud Azure 和 Azure SDK,且模式不互斥。 因此,你可以繼續在 Spring 應用程式中使用 Storage Queue Java 用戶端 API。
新增依賴性
要安裝 Spring Cloud Azure 儲存體 Queue Starter 模組,請在您的 pom.xml 檔案中新增以下相依關係:
Spring Cloud Azure 物料清單(BOM):
<dependencyManagement> <dependencies> <dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-dependencies</artifactId> <version>7.4.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>注意
如果你用的是 Spring Boot 4.0.x,請把版本設
spring-cloud-azure-dependencies為7.4.0。如果你用的是 Spring Boot 3.5.x,請把版本設
spring-cloud-azure-dependencies為6.5.0。如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設
spring-cloud-azure-dependencies為5.25.0.如果您使用 Spring Boot 2.x,請務必將
spring-cloud-azure-dependencies版本設定為4.20.0。此材料帳單 (BOM) 應該在
<dependencyManagement>檔案的 區段中設定。 這確保所有 Spring Cloud Azure 相依性都使用相同的版本。欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本。
Spring Cloud Azure 佇列儲存體 Queue artifact:
<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter-storage-queue</artifactId> </dependency>
編寫您的應用程式以傳送和接收訊息
本節將展示如何在 Spring 應用程式的情境中使用 Azure 佇列儲存體 用戶端。 您有下列兩個選項:
- 使用 Spring Boot 自動配置,並使用從 Spring 環境中開箱即用的客戶端(建議使用)。
- 以程式設計方式建置用戶端。
透過自動配置,您可以從 Spring 反轉控制(IoC)容器中自動裝配客戶端 Bean。 使用記憶體佇列用戶端進行開發時,此方法提供更有彈性且更有效率的體驗。 自動設定具有下列優點:
自動設定使用 外部化組態 ,讓您可以在不同的環境中使用相同的應用程式程序代碼。
您可以將學習產生器模式的程式委派給 Spring Boot 架構,並將用戶端註冊至應用程式內容。 您只專注於如何依照自己的商務需求使用客戶。
您可以使用健康情況指標來檢查應用程式和內部元件的狀態和健康情況。
下列各節中的程式碼範例會示範如何使用以下介紹的兩種不同方法來運用 QueueClient。
提示
Azure Java 儲存佇列的 SDK 提供多個用戶端與儲存佇列互動。 入門版也會為所有記憶體佇列用戶端和客戶端產生器提供自動設定。 本文僅使用 QueueClient 作為範例。
使用 Spring Boot 自動設定
要向 Azure 儲存體 佇列發送訊息及接收訊息,請依照以下步驟設定應用程式:
設定記憶體帳戶名稱和佇列名稱,如下列範例所示:
spring.cloud.azure.storage.queue.account-name=<your-storage-account-name> spring.cloud.azure.storage.queue.queue-name=<your-storage-queue-name>QueueClient在 Spring 應用程式中插入 ,並呼叫相關的 API 來傳送訊息,如下列範例所示:import com.azure.storage.queue.QueueClient; import com.azure.storage.queue.models.QueueMessageItem; import com.azure.storage.queue.models.SendMessageResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StorageQueueClientApplication implements CommandLineRunner { private final static Logger logger = LoggerFactory.getLogger(StorageQueueClientApplication.class); @Autowired private QueueClient queueClient; public static void main(String[] args) { SpringApplication.run(StorageQueueClientApplication.class, args); } @Override public void run(String... args) { // Using the QueueClient object, call the create method to create the queue in your storage account. queueClient.create(); SendMessageResult sendMessageResult = queueClient.sendMessage("Hello world"); logger.info("Send message id: {}", sendMessageResult.getMessageId()); QueueMessageItem queueMessageItem = queueClient.receiveMessage(); logger.info("Received message: {}", new String(queueMessageItem.getBody().toBytes())); } }啟動應用程式。 啟動之後,應用程式會產生類似下列範例的記錄:
Send message id: ... Received message: Hello world
以程式設計方式建置用戶端
您可以自行建置用戶端豆類,但程式很複雜。 在 Spring Boot 應用程式中,您必須管理屬性、了解產生器模式,以及向 Spring 應用程式內容註冊用戶端。 下列步驟示範如何執行此動作。
在 Spring 應用程式中以程式設計方式建置用戶端,如下列範例所示。 請務必將
<storage-account-name>佔位元取代為您自己的值。import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.storage.queue.QueueClient; import com.azure.storage.queue.QueueClientBuilder; import com.azure.storage.queue.models.QueueMessageItem; import com.azure.storage.queue.models.SendMessageResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StorageQueueClientApplication implements CommandLineRunner { private final static String queueName = "test-queue"; private final static String endpoint = "https://<storage-account-name>.queue.core.windows.net/"; private final static Logger logger = LoggerFactory.getLogger(StorageQueueClientApplication.class); QueueClient queueClient = new QueueClientBuilder() .endpoint(endpoint) .queueName(queueName) .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); public static void main(String[] args) { SpringApplication.run(StorageQueueClientApplication.class, args); } @Override public void run(String... args) { // Using the QueueClient object, call the create method to create the queue in your storage account. queueClient.create(); SendMessageResult sendMessageResult = queueClient.sendMessage("Hello world"); logger.info("Send message id: {}", sendMessageResult.getMessageId()); QueueMessageItem queueMessageItem = queueClient.receiveMessage(); logger.info("Received message: {}", new String(queueMessageItem.getBody().toBytes())); } }啟動應用程式。 啟動之後,應用程式會產生類似下列範例的記錄:
Send message id: ... Received message: Hello world
下列清單顯示此程式代碼缺乏彈性或不夠優雅的原因:
- 儲存體帳戶和佇列名稱會被硬編碼。
- 如果您使用
@Value從 Spring 環境取得組態,則 application.properties 檔案中不能有 IDE 提示。 - 如果您有微服務案例,則必須在每個專案中複製程序代碼,而且很容易犯錯,而且很難保持一致。
幸好,使用 Spring Cloud Azure 不需要自己建置客戶端組件。 相反地,您可以直接插入它們,並使用您已熟悉的設定屬性來設定記憶體佇列。 欲了解更多資訊,請參閱 Spring Cloud Azure 配置屬性。
Spring Cloud Azure 也提供以下針對不同情境的全域配置。 欲了解更多資訊,請參閱 Spring Cloud Azure global configuration properties。
- Proxy 選項。
- 重試選項。
你也可以連接不同的 Azure 雲端。 欲了解更多資訊,請參見 連線至不同的 Azure 雲端。
使用 Spring Messaging 的 Azure 儲存體佇列
Spring Messaging Azure 儲存體 Queue模組支援 Spring Messaging 框架,並支援 Azure 佇列儲存體。
如果你正在使用 Spring Messaging 的 Azure 儲存體佇列,則可以使用 StorageQueueTemplate 功能將訊息非同步及同步地傳送到儲存體佇列。
以下章節將展示如何使用 Spring Messaging 的 Azure 儲存體 Queue 來發送訊息,並從儲存佇列接收訊息。
新增依賴性
要安裝 Spring Messaging Azure 儲存體 Queue 模組,請在你的 pom.xml 檔案中新增以下相依關係:
Spring Cloud Azure 物料清單(BOM):
<dependencyManagement> <dependencies> <dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-dependencies</artifactId> <version>7.4.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>注意
如果你用的是 Spring Boot 4.0.x,請把版本設
spring-cloud-azure-dependencies為7.4.0。如果你用的是 Spring Boot 3.5.x,請把版本設
spring-cloud-azure-dependencies為6.5.0。如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設
spring-cloud-azure-dependencies為5.25.0.如果您使用 Spring Boot 2.x,請務必將
spring-cloud-azure-dependencies版本設定為4.20.0。此材料帳單 (BOM) 應該在
<dependencyManagement>檔案的 區段中設定。 這確保所有 Spring Cloud Azure 相依性都使用相同的版本。欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本。
Spring Cloud Azure 啟動程式與 Spring 訊息儲存佇列的產物:
<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter</artifactId> </dependency> <dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-messaging-azure-storage-queue</artifactId> </dependency>
編寫您的應用程式以傳送和接收訊息
使用下列步驟來設定和撰寫應用程式的程式代碼:
請設定 Azure 儲存體 帳號名稱以儲存佇列,如以下範例所示:
spring.cloud.azure.storage.queue.account-name=<your-storage-account-name>使用 Spring 連接傳送者和接收者來傳送和接收訊息,如下列範例所示。 請務必將
<storage-queue-name>佔位元取代為您自己的值。import com.azure.spring.messaging.AzureHeaders; import com.azure.spring.messaging.checkpoint.Checkpointer; import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import java.time.Duration; @SpringBootApplication public class StorageQueueMessagingApplication implements CommandLineRunner { private static final Logger LOGGER = LoggerFactory.getLogger(StorageQueueMessagingApplication.class); private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>"; @Autowired StorageQueueTemplate storageQueueTemplate; public static void main(String[] args) { SpringApplication.run(StorageQueueMessagingApplication.class, args); } @Override public void run(String... args) { storageQueueTemplate .sendAsync(STORAGE_QUEUE_NAME, MessageBuilder.withPayload("Hello world").build()) .subscribe(); LOGGER.info("Message was sent successfully."); Message<?> message = storageQueueTemplate.receiveAsync(STORAGE_QUEUE_NAME, Duration.ofSeconds(30)).block(); LOGGER.info("Received message: {}", new String((byte[]) message.getPayload())); } }啟動應用程式。 啟動之後,應用程式會產生類似下列範例的記錄:
Message was sent successfully. ... Received message: Hello World
使用 Spring Integration 與 Azure 儲存體佇列
Spring Integration Azure 儲存體 Queue模組提供對 Spring Integration 框架的支援,並支援儲存佇列。
如果您的 Spring 應用程式使用 Spring Integration 訊息通道,您可以使用通道配接器,在訊息通道和儲存佇列之間路由訊息。 輸入通道配接器會將訊息從記憶體佇列轉送至訊息通道。 輸出通道配接器會將訊息從訊息通道發佈至記憶體佇列。
以下章節將示範如何使用 Spring Integration 的 Azure 儲存體 Queue 來與儲存佇列之間發送與接收訊息。
新增依賴性
要安裝 Spring Integration Azure 儲存體 Queue 模組,請將以下相依關係加入你的 pom.xml 檔案:
Spring Cloud Azure 物料清單(BOM):
<dependencyManagement> <dependencies> <dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-dependencies</artifactId> <version>7.4.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>注意
如果你用的是 Spring Boot 4.0.x,請把版本設
spring-cloud-azure-dependencies為7.4.0。如果你用的是 Spring Boot 3.5.x,請把版本設
spring-cloud-azure-dependencies為6.5.0。如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設
spring-cloud-azure-dependencies為5.25.0.如果您使用 Spring Boot 2.x,請務必將
spring-cloud-azure-dependencies版本設定為4.20.0。此材料帳單 (BOM) 應該在
<dependencyManagement>檔案的 區段中設定。 這確保所有 Spring Cloud Azure 相依性都使用相同的版本。欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本。
Spring 整合 Azure 儲存佇列工件:
<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter-integration-storage-queue</artifactId> </dependency>
編寫您的應用程式以傳送和接收訊息
使用下列步驟來設定和撰寫應用程式的程式代碼:
請設定 Azure 儲存體 帳號名稱來設定儲存佇列。
spring.cloud.azure.storage.queue.account-name=<your-storage-account-name>建立一個新的
QueueReceiveConfigurationJava 類別,如下範例所示。 這個類別是用來定義訊息接收者。 請務必將<storage-queue-name>佔位元取代為您自己的值。import com.azure.spring.integration.storage.queue.inbound.StorageQueueMessageSource; import com.azure.spring.messaging.AzureHeaders; import com.azure.spring.messaging.checkpoint.Checkpointer; import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.InboundChannelAdapter; import org.springframework.integration.annotation.Poller; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.handler.annotation.Header; @Configuration public class QueueReceiveConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(QueueReceiveConfiguration.class); private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>"; private static final String INPUT_CHANNEL = "input"; @Bean @InboundChannelAdapter(channel = INPUT_CHANNEL, poller = @Poller(fixedDelay = "1000")) public StorageQueueMessageSource storageQueueMessageSource(StorageQueueTemplate storageQueueTemplate) { return new StorageQueueMessageSource(STORAGE_QUEUE_NAME, storageQueueTemplate); } @ServiceActivator(inputChannel = INPUT_CHANNEL) public void messageReceiver(byte[] payload, @Header(AzureHeaders.CHECKPOINTER) Checkpointer checkpointer) { String message = new String(payload); LOGGER.info("Received message: {}", message); } }建立一個新的
QueueSendConfigurationJava 類別,如下範例所示。 這個類別是用來定義訊息傳送者。 請務必將<storage-queue-name>佔位元取代為您自己的值。import com.azure.spring.integration.core.handler.DefaultMessageHandler; import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.MessageHandler; import org.springframework.util.concurrent.ListenableFutureCallback; @Configuration public class QueueSendConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(QueueSendConfiguration.class); private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>"; private static final String OUTPUT_CHANNEL = "output"; @Bean @ServiceActivator(inputChannel = OUTPUT_CHANNEL) public MessageHandler messageSender(StorageQueueTemplate storageQueueTemplate) { DefaultMessageHandler handler = new DefaultMessageHandler(STORAGE_QUEUE_NAME, storageQueueTemplate); handler.setSendCallback(new ListenableFutureCallback<Void>() { @Override public void onSuccess(Void result) { LOGGER.info("Message was sent successfully."); } @Override public void onFailure(Throwable ex) { LOGGER.info("There was an error sending the message."); } }); return handler; } @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL) public interface StorageQueueOutboundGateway { void send(String text); } }使用 Spring 連接傳送者和接收者來傳送和接收訊息。
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.integration.config.EnableIntegration; @SpringBootApplication @EnableIntegration @Configuration(proxyBeanMethods = false) public class StorageQueueIntegrationApplication { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(StorageQueueIntegrationApplication.class, args); QueueSendConfiguration.StorageQueueOutboundGateway storageQueueOutboundGateway = applicationContext.getBeanQueueSendConfiguration.StorageQueueOutboundGateway.class); storageQueueOutboundGateway.send("Hello World"); } }提示
請記得新增
@EnableIntegration批注,以啟用 Spring Integration 基礎結構。啟動應用程式。 啟動之後,應用程式會產生類似下列範例的記錄:
Message was sent successfully. Received message: Hello World
部署到 Azure Spring 應用程式
現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring 應用程式 讓 Spring Boot 應用程式部署到 Azure 變得簡單,無需修改程式碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員可以專注於處理程式碼。 Azure Spring 應用程式 提供生命週期管理,包含全面的監控與診斷、組態管理、服務發現、CI/CD 整合、藍綠部署等多項功能。 要將您的應用程式部署到 Azure Spring 應用程式,請參見 將您的第一個應用程式部署至 Azure Spring 應用程式。
下一步
另請參閱
欲了解更多 Microsoft Azure Spring Boot 起始器的資訊,請參閱 什麼是 Spring Cloud Azure?