SpringCloud Stream的使用
一、SpringCloud Stream简介
在实际开发中,有各式各样的消息处理中间件(MQ),而如果学习所有MQ则学习成本太高,而SpringCloud Stream的出现正是可以无视底层使用的消息中间件的差异,降低切换成本,统一消息的编程模型。
Spring Cloud Stream is a framework for building highly scalable event-driven microservices connected with shared messaging systems.
The framework provides a flexible programming model built on already established and familiar Spring idioms and best practices, including support for persistent pub/sub semantics, consumer groups, and stateful partitions.
Spring Cloud Stream是一个框架,用于构建连接到共享消息传递系统的高度可伸缩的事件驱动微服务。
该框架提供了一个灵活的编程模型,它建立在已经建立和熟悉的Spring习惯用法和最佳实践之上,包括对持久发布/子语义、消费者组和有状态分区的支持。
1.Stream运用方式
交互方式:
- 应用程序通过inputs 或者outputs来与Spring Cloud Stream中binder对象交互。
- 配置binding(绑定)后,Spring Cloud Stream的binder对象与消息中间件交互。
所以,我们只需要与Spring Cloud Stream交互,然后这个中间件会帮我们进行转化,交互。
通过使用Spring Integration来连接消息代理中间件以实现消息事件驱动。
目前仅支持RabbitMQ、Kafka.
二、Binder简介
绑定器Binder作为中间层,实现了应用程序与消息中间件细节之间的隔离(对应于rabbitMQ的exchange,对应于kafka的Topic)
binder中inputs对应消息消费者
binder中outputs对应消息生产者
三、Stream常用注解
@Input
注解标识输入通道,通过该输入通道收到的信息进入应用程序
@Output
注解标识输出通道,发布的消息将通过该通道离开应用程序
@StreamListener
监听队列,用于消费者的队列消息接收
@EnableBinding
指信道chennel和exchange绑定在一起
四、Stream操作
1.构建消息生产者
1.构建子模块
2.修改pom文件
加入了spring-cloud-starter-stream-rabbit
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<!--基础配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency