SpringCloud核心组件之 Spring Cloud Stream消息驱动组件

SpringCloud核心组件之 Spring Cloud Stream消息驱动组件

在实际开发过程中,服务与服务之间通信经常会使用到消息中间件,而以往使用了中间件比如RabbitMQ,那么该中间件和系统的耦合性就会非常高,如果我们要替换为Kafka那么变动会比较大,这时我们可以使用SpringCloudStream来整合我们的消息中间件,来降低系统和中间件的耦合性。

本文主要讲述了如何使用 Spring Cloud Stream消息驱动组件

一、Stream消息通信方式及编程模型
如下的注解无非在做一件事,把我们结构图中那些组成部分上下关联起来,打通通道(如此服务生产者的message数据才能进入mq,mq中数据才能进入服务消费者)。

注解描述
@Input(在消费者工程中使用)注解标识输入通道,通过该输入通道接收到的 消息进入应用程序
@Output(在生产者工程中使用)注解标识输出通道,发布的消息将通过该通道 离开应用程序
@StreamListener(在消费者工程中使用,监 听message的到来)监听队列,用于消费者的队列的消息的接收 (有消息监听…)
@EnableBinding把Channel和Exchange(对于RabbitMQ)绑 定在一起

二、Spring Cloud Stream 应用
首先,我们创建两个工程(基于RabbitMQ,RabbitMQ的安装和使用这里不作说明,默认本机RabbitMQ是启动的)

meander-cloud-provider, 端口:8764,作为生产者端发消息
meander-cloud-consumer,端口:8765和8766,作为消费者端接收消息(启动两个消费者服务,端口分别为8765、8766)

1、Stream消息驱动之开发生产者端

1) meander-cloud-provider 模块中的pom.xml添加依赖(仅列出了与Stream相关的关键依赖,采用eureka作为注册中心)

<!--eureka client 客户端依赖引入-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--spring cloud stream 依赖(rabbit)-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

2)application.yml添加配置

server:
  port: 8764

spring:
  application:
    name: meander-cloud-provider-service
  cloud:
     stream:
      binders: # 绑定MQ服务信息(此处我们是RabbitMQ)
        myRabbitBinder: # 给Binder定义的名称,用于后面的关联
          type: rabbit # MQ类型,如果是Kafka的话,此处配置kafka
          environment: # MQ环境配置(用户名、密码等)
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
      bindings: # 关联整合通道和binder对象
        output: # output是我们定义的通道名称,此处不能乱改
          destination: myExchange # 要使用的Exchange名称(消息队列主题topic名称)
          content-type: application/json # 消息类型设置,比如json. text/plain 表示文本类型
          binder: myRabbitBinder # 关联MQ服务 
          group: myRabbitGroup

eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      #eureka注册中心的端口地址
      defaultZone: http://${eureka.instance.hostname}:8761/eureka

3)启动类:

@EnableEurekaClient
@SpringBootApplication
public class MeanderCloudProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(MeanderCloudProviderApplication.class, args);
    }
 }   

4)业务类开发(发送消息接口、接口实现类、Controller)
业务接口:

public interface MessageProducer {
    public void sendMessage(String msg);
}

业务接口实现类:

// Source.class里面就是对输出通道的定义(这是Spring Cloud Stream内置的通道封装)
@EnableBinding(Source.class)
public class MessageProducerImpl implements MessageProducer {

    // 将MessageChannel的封装对象Source注入到这里使用
    @Autowired
    private Source source;
    
    @Override
    public void sendMessage(String msg) {
        // 向mq中发送消息(并不是直接操作mq,应该操作的是spring cloud stream)
        // 使用通道向外发出消息(指的是Source里面的output通道)
        source.output().send(MessageBuilder.withPayload(msg).build());
    }
}

用于模拟生产消息的测试类Controller:

@RestController
public class SendMessageController {
    @Autowired
    IMessageProducer messageProducer;
    @RequestMapping("/sendMessage")
    public String sendMessage(){
        String serial = UUID.randomUUID().toString();
        String msg = messageProducer.sendMessage(serial);
        System.out.println(msg);
        return msg;
    }
}

2、Stream消息驱动之开发消费者端 meander-cloud-consumer

1)application.yml

server:
  port: 8765

spring:
  application:
    name: meander-cloud-consumer-service
  cloud:
     stream:
      binders: # 绑定MQ服务信息(此处我们是RabbitMQ)
        myRabbitBinder: # 给Binder定义的名称,用于后面的关联
          type: rabbit # MQ类型,如果是Kafka的话,此处配置kafka
          environment: # MQ环境配置(用户名、密码等)
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
      bindings: # 关联整合通道和binder对象
        input: # output是我们定义的通道名称,此处不能乱改
          destination: myExchange # 要使用的Exchange名称(消息队列主题topic名称)
          content-type: application/json # 消息类型设置,比如json. text/plain 表示文本类型
          binder: myRabbitBinder # 关联MQ服务 
          group: myRabbitGroup

eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      #eureka注册中心的端口地址
      defaultZone: http://${eureka.instance.hostname}:8761/eureka

2)消息消费者监听,接收消息并处理

@EnableBinding(Sink.class)
public class MessageReceiveService {
    @Value("${server.port}")
    private String serverPort;
    
    @StreamListener(Sink.INPUT)
    public void recevieMessages(Message<String> message) {
        System.out.println("来自端口:" + serverPort + ",接收到的消息:" + message);
    }
}

三、 Stream 自定义消息通道
Stream 内置了两种接口Source和Sink分别定义了 binding 为 “output” 的输入流和 “input” 的输出流, 我们也可以自定义各种输入输出流(通道),但实际我们可以在我们的服务中使用多个binder、多个输入通道和输出通道,然而默认就带了一个input的输入通道和一个output的输出通道,怎么办?

Stream支持自定义消息通道,可参照Source和Sink类,给你的通道定义个自己的名字,多个输入通 道和输出通道是可以写在一个类中的。

定义接口:

public interface MyMessageChannel {

    String INPUT_PAY = "inputpay";
    String OUTPUT_PAY = "outputpay";

    @Input(INPUT_PAY)
    SubscribableChannel inputPay();

    @Output(OUTPUT_PAY)
    MessageChannel outputPay();

}

如何使用呢?

1、在 @EnableBinding 注解中,绑定自定义的接口

@EnableBinding(MyMessageChannel.class)

2、消费者端使用 @StreamListener 做监听的时候,需要指定 @StreamListener(CustomChannel.INPUT_PAY)

四、Stream 消息分组
如上我们的情况,消费者端有两个(消费同一个MQ的同一个topic主题),但我们实际业务场景中希望这个主题的一个Message只能被一个消费者端消费处理,即一个消息不能被重复消费,此时我们就可以使用消息分组。

我们仅仅需要在服务消费者端设置 spring.cloud.stream.bindings.input.group 属性,多个消费者实例 配置为同一个group名称(在同一个group中的多个消费者只有一个可以获取到消息并消费)。
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值