农场主的黑科技.

Spring Cloud中使用RabbitMQ的两种方式

字数统计: 533阅读时长: 3 min
2018/11/19 Share

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
//接收消息, 自动创建并绑定Queue和Exchange,key . Exchange会把routingKey = key 的消息都传到myQueue中
@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 #默认是把对象进行base64编码后在mq中传递,改为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")
// @SendTo("myMessage2") //再次转发给另一个
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 构建消息驱动微服务

CATALOG
  1. 1. Docker安装RabbitMQ
  2. 2. 第一种方式: 通过AmqpTemplate
    1. 2.1. 加依赖
    2. 2.2. 加yml
    3. 2.3. 接收方
    4. 2.4. 发送方
  3. 3. 第二种方式 : 通过spring cloud stream
    1. 3.1. 加依赖
    2. 3.2. 发送方yml
    3. 3.3. 接收方yml
    4. 3.4. 定义接口
    5. 3.5. 接收方
    6. 3.6. 发送方