演習 - 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 スターターのために Maven 依存関係を追加する
spring-receiver-application
の pom.xml
ファイルで、dependencies の下に次のコマンドを追加します。
<!-- 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 アプリケーションを起動します。 この手順では、mvn
が Windows コンピューターにインストールされていて、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>