Spring Cloud学习笔记【九】消息驱动Stream的使用与详解

                     Spring Cloud学习笔记【九】消息驱动Stream的使用与详解

 一、Stream简介

官方定义如下:

Spring Cloud Stream是一个框架,用于构建与共享消息传递系统连接的高度可伸缩的事件驱动微服务。该框架提供了一个灵活的编程模型,它建立在已经建立和熟悉的Spring熟语和最佳实践上,包括对持久性的Pub/Sub语义消费组状态分区的支持。

通过使用 Spring Cloud Stream,可以有效简化开发人员对消息中间件的使用复杂度,让系统开发人员可以有更多的精力关注于核心业务逻辑的处理。但是目前 Spring Cloud Stream 只支持 RabbitMQ 和 Kafka 的自动化配置。

应用程序通过input和output通道与Binder进行交互,Binder和中间件进行交互,Binder是Stream中的抽象概念,是应用程序和中间件的联合器,使用Binder最方便的是对于消息中间件的进一步封装,可以动态的切换中间件,对于代码层面做到无感知,但是目前 Spring Cloud Stream 只支持 RabbitMQ 和 Kafka 的自动化配置。

二、编码

a.添加依赖(rabbitMq)

implementation 'org.springframework.cloud:spring-cloud-starter-stream-rabbit'
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

b.配置文件 

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  datasource:
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/order?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

c.定义统一的接发接口

扫描二维码关注公众号,回复: 9121098 查看本文章
public interface StremClient {
    
    String INPUT= "myMessage";

    @Input(StremClient.INPUT)
    SubscribableChannel input();

    @Output(StremClient.INPUT)
    MessageChannel output();
}

 b.接收端

@Component
@EnableBinding(StremClient.class)
public class StreamReceiver {

    @StreamListener(StremClient.INPUT)
    public void process(Object msg) {
        System.out.println("接收端接受的消息为:" + msg);
    }
}

e.发送端

@RestController
public class SendMessageController {

    @Autowired
    private StremClient stremClient;

    @RequestMapping("/sendMsg")
    public void process() {
        String message = "发送端发送的消息为:" + new Date();
        System.out.println(message);
        stremClient.output().send(MessageBuilder.withPayload("now " + message).build());
    }
}

f.启动测试 

rabbitMq的队列中已经自动加上了myMessge队列!

日志查看:

在生产环境中,为防止单点故障,多个接收端同时存在,这种编码情况,然而发送端发送消息,所有的接收端都会接收到,然而如果只需要单个接收端接收到需要进行分组设置。

spring:
  cloud:
    stream:
      binders:
        myMessage:
          group: myGroup
          content-type: application/json
发布了71 篇原创文章 · 获赞 31 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/BThinker/article/details/103973413
今日推荐