Spring BootとSpring AMQPを使用してRabbitMQの送受信を行う。hello worldレベルのことをやる。ドキュメント的には https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#boot-features-amqp のあたり。
準備
RabbitMQのインストールとGUIの管理画面を使えるようにしておく。
依存性の追加
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> </dependencies>
設定
ローカルにRabbitMQをインストールしてデフォルト設定の場合、特に何も設定しなくても良い。別マシンに接続するとか、ID・パスワードを入れるとかの場合、externalized configurationで設定する。以下はapplication.yamlでの設定例。
spring: rabbitmq: host: 192.168.10.23 port: 5672 username: kagamihoge password: xxxxxx main: web-environment: false
RabbitMQと直接の関係は無いが、web関連は不要なんでspring.main.web-environment=falseで抑制しておく。
指定可能な値の一覧 -> https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties
受信
package kagamihoge.receive; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ReceiverApplication { public static void main(String[] args) throws InterruptedException { SpringApplication.run(ReceiverApplication.class, args); } @RabbitListener(queues = "sample-queue") public void receive(String msg) { System.out.println(msg); } }
動かす前に http://localhost:15672 の管理コンソールからキューを、sample-queueという名前で、新規作成しておく。
動作確認は管理コンソールからメッセージ送信する。sample-queueを選んでPublish messageする。Propertiesにcontent_type=text/plainと入れればbyte[]じゃなくて文字列を送信できる。
送信
package kagamihoge.send; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; 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 SenderApplication implements CommandLineRunner { public static void main(String[] args) throws InterruptedException { SpringApplication.run(SenderApplication.class, args).close();; } @Autowired AmqpTemplate amqpTemplate; @Override public void run(String... args) throws Exception { Message message = new Message("msg".getBytes(), new MessageProperties()); amqpTemplate.send("sample-exchange", null, message); } }
動かす前に管理コンソールでexchangeをsample-exchangeという名前で作り、sample-queueにバインドさせておく。
受信側を起動させておいて、上の送信のコードを動かす。sample-exchangeに送信したメッセージがsample-queueに入って、それを受信、という流れが確認できる。