演習 - Azure Service Bus にメッセージを送信する
このユニットでは、Azure Service Bus キューにメッセージを送信する Spring Boot アプリケーションを作成します。 次の手順をローカルで完了します。
Spring Boot プロジェクトを作成する
Spring Boot プロジェクトを作成するには、次のコマンド ラインで Spring Initializr を使用します。
curl https://start.spring.io/starter.tgz -d type=maven-project -d dependencies=web -d baseDir=spring-sender-application -d bootVersion=3.3.0.RELEASE -d javaVersion=1.8 | tar -xzvf -
Service Bus キューにメッセージを送信する
次に、いくつかのメッセージを Service Bus キューに送信してみましょう。
Service Bus Spring Boot Starter の maven 依存関係を追加する
spring-sender-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-sender-application\src\main\resources
フォルダーで、application.properties
ファイルを編集し、次のパラメーターを追加します。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
で、次の内容を含む SendController.java
ファイルを作成します。
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SendController {
private static final String queue = "test-queue-jms";
@Autowired
private JmsTemplate jmsTemplate;
@GetMapping("/messages")
public String postMessage(@RequestParam String message) {
jmsTemplate.send(queue, s -> s.createTextMessage(message));
return message;
}
}
ローカルでアプリケーションを実行する
pom.xml
ファイルがあるサンプルspring-sender-application
フォルダーのルートに戻り、次のコマンドを実行して Spring Boot アプリケーションを起動します。 この手順では、Windows コンピューターにmvn
がインストールされており、PATH
にインストールされていることを前提としています。mvn spring-boot:run
アプリケーションの起動が完了したら、次のリンクを選択して、Service Bus キューにメッセージを送信できます。
http://localhost:8080/messages?message=Hello
http://localhost:8080/messages?message=HelloAgain
http://localhost:8080/messages?message=HelloOnceAgain
メッセージ クエリ パラメーターの文字列値を変更し、任意のテキストを Service Bus キューに送信できます。
ブラウザーには、メッセージ クエリ文字列パラメーターとして渡されたものが表示されます。これは、Service Bus がメッセージを受け入れることを意味します。
Service Bus キューのメッセージを表示する
注
メッセージを表示すると、メッセージの送信側を理解するのに役立ちますが、この手順は省略可能です。
これらのメッセージは、このチュートリアルの次の手順で受信されます。
Azure portal の Service Bus エクスプローラーでメッセージの表示に進むことができます。