rabbitmq在springboot(cloud)中AmqpTemplate和Spring Cloud Stream的简单使用
Docker安装RabbitMQ
使用docker搭建RabbitMQ
1 2 3 4 5 6 7 8
| #!/usr/bin/env bash
#default username/password = guest/guest # 15672 浏览器能访问的管理界面 # 5672 在项目中配置这个端口 docker stop my-rabbitmq docker rm my-rabbitmq docker run -d --name my-rabbitmq --hostname my-rabbit-mq -p 5672:5672 -p 15672:15672 rabbitmq:3.7.8-management
|
第一种方式: 通过AmqpTemplate
加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
|
加yml
发送方接收方都需要配置
1 2 3 4 5 6
| spring: rabbitmq: host: localhost port: 5672 username: guest password: guest
|
接收方
1 2 3 4 5 6 7 8 9
| @RabbitListener(bindings = @QueueBinding( exchange = @Exchange("myExchange"), key = "key", value = @Queue("myQueue") )) public void process(){
}
|
发送方
1 2 3 4 5 6 7
| @Autowired private AmqpTemplate amqpTemplate;
public void send(){ amqpTemplate.convertAndSend("myExchange","key",new Object()); }
|
第二种方式 : 通过spring cloud stream
stream是springcloud对mq的封装,目前只支持rabbitmq和kafka
加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-rabbit</artifactId> </dependency>
|
##
发送方yml
1 2 3 4 5 6 7 8 9 10 11
| spring: rabbitmq: host: localhost port: 5672 username: guest password: guest cloud: stream: bindings: message-output: content-type: application/json
|
接收方yml
1 2 3 4 5 6 7 8 9 10 11
| spring: rabbitmq: host: localhost port: 5672 username: guest password: guest cloud: stream: bindings: message-input: group: order
|
定义接口
1 2 3 4 5 6 7
| public interface StreamClient { @Input("message-input") SubscribableChannel input();
@Output("message-output") MessageChannel output(); }
|
接收方
1 2 3 4 5 6 7 8 9 10 11
| @Component @EnableBinding(StreamClient.class) public class StreamReceiver {
@StreamListener("message-input")
public String process(Object message){ System.out.println("StreamReceiver "+message); return "receive"; } }
|
发送方
1 2 3 4 5 6 7 8 9 10
| @Component @EnableBinding(StreamClient.class) public class StreamReceiver { @Autowired private StreamClient streamClient;
public void process(){ streamClient.output().send(MessageBuilder.withPayload("now"+new Date()).build()); } }
|
相关资料 : 使用 Spring Cloud Stream 构建消息驱动微服务