Stream消息驱动
一、Stream介绍:
Spring Cloud Stream 是一个构建消息驱动微服务应用的框架。
Stream 解决了开发人员无感知的使用消息中间件的问题,因为Stream对消息中间件的进一步封装,可以做到代码层面对中间件的无感知,甚至于动态的切换中间件,使得微服务开发的高度解耦,服务可以关注更多自己的业务流程。(就像JDBC一样的感觉)
Spring Cloud Stream目前支持两种消息中间件RabbitMQ和Kafka
其实就是想用同一套的代码去使用不同的MQ
Spring Cloud Stream 构建的应用程序与消息中间件之间是通过绑定器 Binder 相关联的。绑定器对于应用程序而言起到了隔离作用, 它使得不同消息中间件的实现细节对应用程序来说是透明的。
binding 是我们通过配置把应用和spring cloud stream 的 binder 绑定在一起
output:发送消息 Channel,内置 Source接口
input:接收消息 Channel,内置 Sink接口
二、Stream消息生产者
1.创建消息生产者模块,引入依赖 starter-stream-rabbit
<!--spring boot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- stream -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
2.编写配置,定义 binder,和 bingings
server:
port: 8000
spring:
cloud:
stream:
# 定义绑定器,绑定到哪个消息中间件上
binders:
itheima_binder: # 自定义的绑定器名称
type: rabbit # 绑定器类型
environment: # 指定mq的环境
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /
bindings:
output: # channel名称
binder: itheima_binder #指定使用哪一个binder
destination: itheima_exchange # 消息目的地
3.定义消息发送业务类。添加 @EnableBinding(Source.class),注入MessageChannel output ,完成消息发送
@Component
@EnableBinding(Source.class)
public class MessageProducer {
@Autowired
private MessageChannel output;
public void send(){
String message="hello Stream~~~";
//发送消息
output.send(MessageBuilder.withPayload(message).build());
System.out.println("消息发送成功~~~");
}
}
@RestController
public class ProducerController {
@Autowired
private MessageProducer messageProducer;
@RequestMapping("/send")
public String sendMsg(){
messageProducer.send();
return "success";
}
}
4.编写启动类,测试
三、Stream消息消费者
步骤:
1.创建消息消费者模块,引入依赖 starter-stream-rabbit
<!-- stream -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
2.编写配置,定义 binder,和 bingings
server:
port: 9000
spring:
cloud:
stream:
# 定义绑定器,绑定到哪个消息中间件上
binders:
itheima_binder: # 自定义的绑定器名称
type: rabbit # 绑定器类型
environment: # 指定mq的环境
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /
bindings:
input: # channel名称
binder: itheima_binder #指定使用哪一个binder
destination: itheima_exchange # 消息目的地
修改了端口号和input,其他的没改
3.定义消息接收业务类。添加 @EnableBinding(Sink.class),使用@StreamListener(Sink.INPUT),完成消息接收。
/*
消息接收类
*/
@EnableBinding({Sink.class})
@Component
public class MessageListener {
@StreamListener(Sink.INPUT)
public void receive(Message message){
System.out.println(message);
System.out.println(message.getPayload());
}
}
4.编写启动类,测试
producer和consumer都得启动,然后先访问producer,地址是:localhost:8000/send
这样producer就发送了消息了
然后我们就在consumer端能够接收到消息信息了!