演習 - Azure Service Bus からメッセージを受信する
次に、Azure Service Bus キューからメッセージを受信できる Spring Boot アプリケーションを作成しましょう。
Spring Boot プロジェクトを作成する
新しいターミナル ウィンドウを開いてみましょう。送信側の Spring Boot アプリケーションと同様に、 Spring Initializr を使用して Spring Boot プロジェクトを作成します。
curl https://start.spring.io/starter.tgz -d type=maven-project -d dependencies=web -d baseDir=spring-receiver-application -d bootVersion=3.3.0.RELEASE -d javaVersion=1.8 | tar -xzvf -
Service Bus キューからメッセージを受信する
ここでも、依存関係と構成を追加します。
Service Bus Spring Boot Starter の maven 依存関係を追加する
spring-receiver-application
のpom.xml
ファイルで、依存関係の下に次のコマンドを追加します。
<!-- https://mvnrepository.com/artifact/com.azure.spring/spring-cloud-azure-starter-servicebus-jms -->
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-servicebus-jms</artifactId>
<version>5.18.0</version>
</dependency>
構成パラメーターを追加する
spring-receiver-application\src\main\resources
フォルダーで、application.properties
ファイルを編集し、次のパラメーターを追加します。server.port=9090 spring.jms.servicebus.connection-string=<xxxxx> spring.jms.servicebus.idle-timeout=20000 spring.jms.servicebus.pricing-tier=premium
spring.jms.servicebus.connection-string
プロパティを、前に保存した Service Bus 名前空間への接続文字列に設定します。
Service Bus からメッセージを受信するコードを追加する
次に、Service Bus キューからメッセージを受信するビジネス ロジックを追加します。
src/main/java/com/example/demo
ディレクトリに、次の内容を含むReceiveController.java
ファイルを作成します。
package com.example.demo;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class ReceiveController {
@JmsListener(destination = "test-queue-jms")
public void receiveMessage(String message) {
System.out.println("Received <" + message + ">");
}
}
ローカルでアプリケーションを実行する
pom.xml
ファイルがあるサンプルspring-receiver-application
フォルダーのルートに戻り、次のコマンドを実行して Spring Boot アプリケーションを起動します。 この手順では、Windows コンピューターにmvn
がインストールされており、PATH
にインストールされていることを前提としています。mvn spring-boot:run
アプリケーションの起動が完了すると、コンソール ウィンドウに次のログ ステートメントが表示されます。
Received <Hello> Received <HelloAgain> Received <HelloOnceAgain>
ステートメントの外観は、Spring Boot アプリケーションが Service Bus キューからメッセージを正常に受信していることを示しています。
ワークフロー全体の動作を確認する
送信側アプリケーション (ユニット 4) がまだ実行されている場合は、次のリンクを選択して、Service Bus キューにメッセージを送信できます。
http://localhost:8080/messages?message=HelloOnceAgainAndAgain
受信側アプリケーションが Service Bus キューからメッセージを受信し、コンソールに表示します。
Received <HelloOnceAgainAndAgain>