Spring Cloud Stream
消息中间件主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。不同的中间件其实现方式,内部结构是不一样的。
如果用了两个消息队列的其中一种,后面的业务需求,我想往另外一种消息队列进行迁移,这时候无疑就是一个灾难性的,一大堆东西都要重新推倒重新做,因为它跟我们的系统耦合了,这时候springcloud Stream 给我们提供了一种解耦合的方式。
Spring Cloud Stream由一个中间件中立的核组成。应用通过Spring Cloud Stream插入的input(相当于消费者consumer,它是从队列中接收消息的)和output(相当于生产者producer,它是从队列中发送消息的。)通道与外界交流。通道通过指定中间件的Binder实现与外部代理连接。业务开发者不再关注具体消息中间件,只需关注Binder对应用程序提供的抽象概念来使用消息中间件实现业务即可。
最底层是消息服务;中间层是绑定层,绑定层和底层的消息服务进行绑定,是实现了多种消息中间件的工具,这一层的代码不需要自己写,更改中间件就更换绑定器即可;顶层是消息生产者和消息消费者,顶层可以向绑定层生产消息和和获取消息消费
消息生产者
新建springcloud的stream_producer模块。
使用rabbitmq-server.bat
启动rabbitmq,访问 http://localhost:15672/#/。
-
依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-rabbit</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-rabbit</artifactId> </dependency>
-
application.yml
server: port: 7001 #服务端口 spring: application: name: stream_producer #指定服务名 rabbitmq: addresses: 127.0.0.1 username: guest password: guest cloud: stream: bindings: output: destination: itcast-default #指定消息发送的目的地,在rabbitmq中,发送到一个itcast-default的exchange中 myoutput: #自定义的消息通道,默认是output destination: itcast-custom-output producer: partition-key-expression: payload #分区关键字