SpringCloud-Alibaba之消息驱动Stream

此文章主要讲解springcloud中消息驱动Stream的相关知识。

前言

Spring Cloud Stream 中文指导手册: 点我跳转

在实际的企业开发中,消息中间件是至关重要的组件之一。消息中间件主要解决应用解耦、异步消息、流量削峰等问题,实现高性能、高可用、可伸缩和最终一致性的架构。不同的中间件其实现方式,内部结构是不一样的。如常见的RabbitMQ和Kafka,由于这两个消息中间件的架构上的不同,如RabbitMQ有Exchange,Kafka有Topic、Partitions,这些中间件的差异性导致我们实际项目开发会给我们造成了一定的困扰,我们如果用了两个消息中间件的其中一种,后面的业务需求,需要往另一种消息中间件迁移,这时候无疑就是一个灾难,一大堆东西需要重新推倒重做,因为它和我们系统耦合了,这时候Spring Cloud Stream给我们提供了一种解耦合的方式。

概述

1597725567239

一句话就是屏蔽底层消息中间件的差异,降低切换成本,统一消息的编程模型

就像 JDBC 形成一种规范,统一不同数据库的接口

Spring Cloud Stream由一个中间件中立的Core组成。应用通过Spring Cloud Stream的input(相当于消费者consumer,它是从队列中接收消息的)output(相当于生产者producer,它是从队列中发送消息的)通道和外界交流。通道通过指定中间件的Binder实现和外部代理连接。业务开发者不再关注具体消息中间件,只需要关注Binder对应用程序提供的抽象概念来使用消息中间件实现业务即可。

image-20210120132508659

核心概念

绑定器

  • 绑定器(Binder)是Spring Cloud Stream中的一个非常重要的概念。在没有绑定器这个概念的情况下,我们的SpringBoot应用要直接和消息中间件进行信息交互的时候,由于各个消息中间件构建的初衷不同,它们的实现细节上会有较大的差异性,这似的我们实现的消息交互逻辑就会非常笨重,因此对具体的中间件实现细节有太重的依赖,当中间件有较大的变动升级、或者更换中间件的时候,我们就需要付出非常大的代价来实施。

  • 通过定义绑定器作为中间层,实现了应用程序和消息中间件细节之间的隔离。通过向应用程序暴露统一的Channel,使得应用程序不需要再考虑各种不同的消息中间件实现。当需要升级消息中间件或者更换其他的消息中间件产品时,我们需要做的就是更换对应的Binder绑定器而不需要修改任何应用逻辑,甚至可以任意的改变中间件的类型而不需要修改一行代码。

  • Spring Cloud Stream支持各种Binder实现,如下图所示:

image-20210120132541960

  • 通过配置把应用和Spring Cloud Stream的binder绑定在一起,之后我们只需要修改binder的配置来达到动态修改Topic、Exchange、type等一系列信息而不需要修改一行代码。

发布/订阅模型

在Spring Cloud Stream中的消息通信方式遵循了发布--订阅模式,当一条消息被投递到消息中间件之后,它会通过共享的Topic主题进行广播,消息消费者在订阅的主题中收到它并触发自身的业务逻辑处理。

这里所提到的Topic主题是Spring Cloud Stream中的一个抽象概念,用来代表发布共享消息给消费者的地方。在不通过的消息中间件中,Topic可能对应着不同的概念,如:在RabbitMQ中它对应了Exchange,在Kafka中对应了Topic

标准流程套路

image-20210120132718922

  • Middleware:中间件,目前只支持RabbitMQ和Kafka

  • Binder:Binder是应用和消息中间件之间的封装,目前实现了Kafka和RabbitMQ的Binder,通过Binder可以很方便的连接中间件,可以动态的改变消息类型(对应于Kafka的TopicRabbitMQ的Exchange),这些都是可以通过配置文件来实现。

  • @Input:注解标识输入通道,通过该输入通道接收到的消息进入应用程序。

  • @Output:注解标识输出通道,发布的消息将通过该通道离开应用程序。

  • @StreamListener:监听队列,用于消费者的队列的消息接收。

  • @EnableBinding:将通道Channel和Exchange绑定在一起。

image-20210120132818666

  • Binder:很方便的连接中间件,屏蔽差异。

  • Channel:通道,是队列Queue的一种抽象,在消息通讯系统中就是实现存储和转发的媒介,通过对Channel实现对队列进行配置。

  • Source和Sink:简单可以理解为参照对象就是Spring Cloud Stream本身,从Spring Cloud Stream发布消息就是输出,从Spring Cloud Stream接受消息就是输入。

入门案例

准备工作

RabbitMQ环境先准备好。

消息生产者

新建模块

cloud-stream-rabbitmq-provider8801

POM文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring_cloud_atguigu_2020</artifactId>
        <groupId>com.itjing.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-stream-rabbitmq-provider8801</artifactId>

    <dependencies>
        <!-- stream-rabbit -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <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.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
YML文件
server:
  port: 8801
spring:
  application:
    name: cloud-stream-provider
  cloud:
    stream:
      binders: # 在此配置要绑定的rabbitMQ的服务信息
        defaultRabbit: # 表示定义的名称,用于和binding整合
          type: rabbit  # 消息组件类型
          environment:  # 设置rabbitmq的相关环境配置
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
      bindings:  # 服务的整合处理
        output:   # 表示是生产者,向rabbitMQ发送消息
          destination: rabbit-default  # 指定消息发送的目的地。在RabbitMQ中,发送到一个名为rabbit-default的Exchange上。
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/
  instance:
    lease-renewal-interval-in-seconds: 2 # 设置心跳时间,默认是30秒
    lease-expiration-duration-in-seconds: 5 # 最大心跳间隔不能超过5秒,默认90秒
    instance-id: send-8801.com # 在信息列表显示主机名称
    prefer-ip-address: true # 访问路径变为ip地址

这里有个坑:application.yml使用了spring.cloud.stream.binders.defaultRabbit.environment.spring.rabbitmq.xx来配置rabbitmq的环境。

如果你是用的其他服务器上的rabbitmq,比如我使用的我自己的阿里云服务器然后创建docker容器来运行rabbitmq。

按照上述的配置方式的话,启动时会试图连接两次rabbitmq程序。

第一次试图连接访问的就是application.yml中配置的地址,此时已经订阅成功了

但是程序还会在之后进行第二次连接,此时访问的地址就是localhost:5672,在我的环境中,我本地没有rabbitmq环境,所以直接报IOException。

所以,如果是使用的自己的服务器来配置,则需要修改配置文件,将rabbitmq的配置信息移动到application.yml中的spring节点下

spring:
  application:
    name: cloud-stream-provider
  rabbitmq:
    host: 服务器地址
    port: 5672
    username: guest
    password: guest
  cloud:
    stream:
      binders:
        defaultRabbit:
          type: rabbit
      bindings:
        output:
          destination: cruiiExchange
          content-type: application/json
          binder: defaultRabbit
主启动类
@SpringBootApplication
public class StreamMQMain8801 {
    public static void main(String[] args) {
        SpringApplication.run(StreamMQMain8801.class, args);
    }
}
业务类

此业务类不是以前的service,而是负责推送消息的服务类

发送消息接口
public interface IMessageProvider {
    void send();
}
接口实现类
package com.itjing.springcloud.service.impl;

import com.itjing.springcloud.service.IMessageProvider;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;

import javax.annotation.Resource;
import java.util.UUID;
/**
 * 发送消息,需要定义一个通道接口,通过接口中内置的 Message Channel。
 * Spring Cloud Stream中内置接口 Source
 * @EnableBinding注解:绑定对应通道
 * 发送消息的话,通过MessageChannel发送消息
 */
// 定义消息的推送管道
@EnableBinding(Source.class)  // 不是和controller打交道的service,而是发送消息的推送服务类
public class IMessageProviderImpl implements IMessageProvider {
    @Resource
    private MessageChannel output; // 消息发送管道

    @Override
    public void send() {
        String serial = UUID.randomUUID().toString();
        //通过MessageBuilder帮助我们创建消息
        output.send(MessageBuilder.withPayload(serial).build());
        System.out.println("******serial: " + serial);
    }
}
Controller
@RestController
public class SendMessageController {
    @Resource
    private IMessageProvider messageProvider;

    @GetMapping("/sendMessage")
    public String sendMessage() {
        messageProvider.send();
        return "send success! ";
    }
}
测试
  1. 启动 Eureka Server 7001
  2. 启动 rabbitMQ
  3. 启动 8801
  4. 在 rabbitMQ 中查看是否有我们发送的消息!

多次访问:http://localhost:8801/sendMessage

打开 rabbitMQ : http://localhost:15672/ ,可见是成功的。

image-20210120145103038

消息消费者

新建模块

cloud-stream-rabbitmq-consumer8802

POM文件
<dependencies>
    <!-- stream-rabbit -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    </dependency>
    <!--eureka-client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <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.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
YML文件

在 stream的配置上,output 改成 input

server:
  port: 8802
spring:
  application:
    name: cloud-stream-consumer
  cloud:
    stream:
      binders: # 在此配置要绑定的rabbitMQ的服务信息
        defaultRabbit: # 表示定义的名称,用于和binding整合
          type: rabbit  # 消息组件类型
          environment:  # 设置rabbitmq的相关环境配置
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
      bindings:  # 服务的整合处理
        input:   # 表示是消费者,通过rabbitMQ接收消息
          destination: rabbit-default  # 从哪获取
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/
  instance:
    lease-renewal-interval-in-seconds: 2 # 设置心跳时间,默认是30秒
    lease-expiration-duration-in-seconds: 5 # 最大心跳间隔不能超过5秒,默认90秒
    instance-id: receive-8802.com # 在信息列表显示主机名称
    prefer-ip-address: true # 访问路径变为ip地址
主启动类
@SpringBootApplication
public class StreamMQMain8802 {
    public static void main(String[] args) {
        SpringApplication.run(StreamMQMain8802.class, args);
    }
}
业务逻辑
@Component
@EnableBinding(Sink.class)
public class ReceiveMessageListenerController {
    @Value("${server.port}")
    private String serverPort;

    //监听binding中的消息
    @StreamListener(Sink.INPUT)
    public void input(Message<String> message) {
        System.out.println("消费者1号,serverport: " + serverPort + ",接受到的消息:" + message.getPayload());
    }
}
测试

启动 8802。

发送消息: http://localhost:8801/sendMessage

消息发送者:

image-20210120151431119

消息接收者:

image-20210120151502832

配置分组消费

概述

通常在生产环境中,我们的每个服务都不会以单节点的方式,当同一个服务启动多个实例的时候,这些实例都会绑定到同一个消息通道的目标主题(Topic)上。默认情况下,当生产者发出一条消息到绑定通道上,这条消息会产生多个副本被每个消费者实例接收和处理,但是有些业务场景下,我们希望生产者的消息只被一个实例消费,这个时候我们需要为这些消费者设置消费组来实现这样的功能。

image-20210120155042490

实操

新建模块 cloud-stream-rabbitmq-consumer8803 ,8803 就是 8802 clone 出来的,只需修改对应的信息就行

重复消费

两个消费者都接收到了消息,这属于重复消费。

  • 例如:消费者进行订单创建,这样就创建了两份订单,会造成系统错误。

注意在 Stream 中处于同一个group 中的多个消费者是竞争关系,就能够保证消息只会被其中一个应用消费一次。

不同组是可以全面消费的(重复消费)。

同一组内会发生竞争关系,只有其中一个可以消费。

Stream默认不同的微服务是不同的组

image-20210120155420091

对于重复消费这种问题,导致的原因是默认每个微服务是不同的group,组流水号不一样,所以被认为是不同组,两个都可以消费。

解决的办法就是自定义配置分组:

消费者 yml 文件配置:

      # 8802 的消费者
      .....
      bindings:  # 服务的整合处理
        input:   # 表示是消费者,通过rabbitMQ接收消息
          destination: rabbit-default  # 指定消息发送的目的地。在RabbitMQ中,发送到一个名为rabbit-default的Exchange上。
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
          group: group1
      .....
      
      
      # 8803 的消费者
      .....
      bindings:  # 服务的整合处理
        input:   # 表示是消费者,通过rabbitMQ接收消息
          destination: rabbit-default  # 指定消息发送的目的地。在RabbitMQ中,发送到一个名为rabbit-default的Exchange上。
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
          group: group1
      .....      
      
      
# 他们的组名相同,设置消息的组名(同名组中的多个消息者,只有一个去消费消息)

当两个消费者配置的 group 相同时,就属于同一组,就不会被重复消费。

image-20210120160206969

持久化

加上group配置,就已经实现了消息的持久化。

  1. 停止 8002 和 8003 ,并去除掉8802的分组,保留8803的分组
  2. 8801 先发送几条消息到 rabbitMQ
  3. 先启动 8802,无分组属性配置,后台没有打印消息
  4. 在启动 8803,有分组属性配置,后台打印出来了MQ上的消息

自定义消息通道

概述

  • Spring Cloud Stream内置类两种接口,分别定义了binding为“input”输入流“output”输出流,而在我们实际使用中,往往需要定义各种输入输出流。使用方法也很简单。

自定义消息通道

消息生产者
修改配置文件
      ......
      bindings:  # 服务的整合处理
        output:   # 表示是生产者,向rabbitMQ发送消息
          destination: rabbit-default  # 指定消息发送的目的地。在RabbitMQ中,发送到一个名为rabbit-default的Exchange上。
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
        # 自定义通道  
        customOutput:
          destination: rabbit-custom
      ......
自定义消息通道
package com.itjing.springcloud.channel;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;

public interface CustomProcessor extends Source, Sink {

    /**
     * 自定义输出通道
     */
    String CUSTOM_OUTPUT = "customOutput";
    /**
     * 自定义输入通道
     */
    String CUSTOM_INPUT = "customInput";

    /**
     * 消息生产者的配置
     *
     * @return
     */
    @Output(CustomProcessor.CUSTOM_OUTPUT)
    MessageChannel customOutput();

    /**
     * 消息消费者的配置
     *
     * @return
     */
    @Input(CustomProcessor.CUSTOM_INPUT)
    SubscribableChannel customInput();
}
发送消息接口
public interface IMessageProvider {
    void send();
}
接口实现类
@EnableBinding(CustomProcessor.class)  // 这里是自定义的 CustomProcessor
public class IMessageProviderImpl implements IMessageProvider {

    @Autowired
    @Qualifier(value = "customOutput")
    private MessageChannel output;

    @Override
    public void send() {
        String serial = UUID.randomUUID().toString();
        //通过MessageBuilder帮助我们创建消息
        output.send(MessageBuilder.withPayload(serial).build());
        System.out.println("******serial: " + serial);
    }
}
业务逻辑
@RestController
public class SendMessageController {
    @Resource
    private IMessageProvider messageProvider;

    @GetMapping("/sendMessage")
    public String sendMessage() {
        messageProvider.send();
        return "send success! ";
    }
}
消息消费者
修改配置文件
      ......
      bindings:  # 服务的整合处理
        intput:   # 表示是消费者
          destination: rabbit-default  # 从哪获取
          content-type: application/json  # 设置消息类型,本次是json,文本是 "text/plain"
          binder: defaultRabbit  # 设置要绑定的消息服务的具体配置
        # 自定义通道  
        customOutput:
          destination: rabbit-custom
      ......
自定义消息通道
package com.itjing.springcloud.channel;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;

public interface CustomProcessor extends Source, Sink {

    /**
     * 自定义输出通道
     */
    String CUSTOM_OUTPUT = "customOutput";
    /**
     * 自定义输入通道
     */
    String CUSTOM_INPUT = "customInput";

    /**
     * 消息生产者的配置
     *
     * @return
     */
    @Output(CustomProcessor.CUSTOM_OUTPUT)
    MessageChannel customOutput();

    /**
     * 消息消费者的配置
     *
     * @return
     */
    @Input(CustomProcessor.CUSTOM_INPUT)
    SubscribableChannel customInput();
}
业务逻辑
@Component
@EnableBinding(value = CustomProcessor.class)
public class ReceiveMessageListenerController {
    @Value("${server.port}")
    private String serverPort;

    @StreamListener(CustomProcessor.CUSTOM_INPUT)
    public void input(Message<String> message) {
        System.out.println("消费者1号,serverport: " + serverPort + ",接受到的消息:" + message.getPayload());
    }
}

测试即可。

消息分区

有一些场景需要满足,同一特征的数据被同一个实例消费,比如同一个id的传感器监测数据必须被同一个实例统计计算分组,否则可能无法获取全部的数据。又比如部分异步任务,首次请求启动task,二次请求取消task,此场景就必须保证两次请求到同一个实例。

image-20210120164902237

消息生产者配置

	  ......
      bindings: # 绑定通道
        output:
          destination: rabbit-default # 指定消息发送的目的地。在RabbitMQ中,发送到一个名为rabbit-default的Exchange上。
          contentType: application/json # 消息的类型
          binder: defaultRabbit
        # 自定义通道
        customOutput:
          destination: rabbit-custom
          producer:
            # ===========修改部分开始===========
            partition-key-expression: payload #通过该参数指定了分组键的表达式规则,我们可以根据实际的输出消息规则来配置SPEL来生成合适的分区键
            partition-count: 2 # 该参数指定了消息分区的数量
            # ===========修改部分结束===========

消息消费者配置

	  ......
      bindings: # 绑定通道
        input:
          destination: rabbit-default # 指定消息获取的目的地。
          contentType: application/json # 消息的类型
          binder: defaultRabbit
          group: group1 # 设置消息的组名(同名组中的多个消息者,只有一个去消费消息)
        # 自定义通道
        customInput:
          destination: rabbit-custom
          group: group2 # 设置消息的组名(同名组中的多个消息者,只有一个去消费消息)
          # ===========修改部分开始===========
          consumer:
            partitioned: true # 开启消费者分区功能
          # ===========修改部分结束===========
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

筱晶哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值