SpringCloud学习之(十五)SpringCloud Stream消息驱动

(十五)SpringCloud Stream消息驱动

1、消息驱动概述

1.1 什么是SpringCloudStream

官方定义Spring Cloud Stream是一个构建消息驱动微服务的框架。

应用程序通过inputs或者 outputs来与Spring Cloud Stream中binder对象交互。

通过我们配置来binding(绑定),而Spring Cloud Stream 的binder对象负责与消息中间件交互。

所以,我们只需要搞清楚如何与Spring Cloud Stream交互就可以方便使用消息驱动的方式。

通过使用Spring Integration来连接消息代理中间件以实现消息事件驱动。

Spring Cloud Stream为一些供应商的消息中间件产品提供了个性化的自动化配置实现,引用了发布-订阅、消费组、分区的三个核心概念。

目前仅支持RabbitMQ、Kafka。

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

官网

  • https://spring.io/projects/spring-cloud-stream#overview
  • https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.1.RELEASE/reference/html/
  • Spring Cloud Stream中文指导手册:
    • https://m.wang1314.com/doc/webapp/topic/20971999.html
1.2 设计思想
1.2.1 标准的MQ

image-20200822175515219

  • 生产者/消费者之间靠消息媒介传递信息内容——Message
  • 消息必须走特定的通道——消息通道MessageChannel
  • 消息通道里的消息如何被消费呢,谁负责收发处理——消息通道MessageChannel的子接口SubscribableChannel,由MessageHandler消息处理器订阅
1.2.2 为什么用Cloud Stream

比方说我们用到了RabbitMQ和Kafka,由于这两个消息中间件的架构上的不同,
像RabbitMQ有exchange,kafka有Topic和Partitions分区,

image-20200822175827900

这些中间件的差异性导致我们实际项目开发给我们造成了一定的困扰,我们如果用了两个消息队列的其中一种,后面的业务需求,我想往另外一种消息队列进行迁移,这时候无疑就是一个灾难性的, 一大堆东西都要重新推倒重新做,因为它跟我们的系统耦合了,这时候springcloud Stream给我们提供了一种解耦合的方式。

1.2.3 stream凭什么可以统一底层差异

在没有绑定器这个概念的情况下,我们的SpringBoot应用要直接与消息中间件进行信息交互的时候,由于各消息中间件构建的初衷不同,它们的实现细节上会有较大的差异性。

通过定义绑定器作为中间层,完美地实现了应用程序与消息中间件细节之间的隔离。
通过向应用程序暴露统一的Channel通道, 使得应用程序不需要再考虑各种不同的消息中间件实现。
通过定义绑定器Binder作为中间层,实现了应用程序与消息中间件细节之间的隔离。

1.2.4 Binder

Stream对消息中间件的进一 步封装,可以做到代码层面对中间件的无感知,甚至于动态的切换中间件(rabbitmq切换为kafka),使得微服务开发的高度解耦,服务可以关注更多自己的业务流程

image-20200822180249243

通过定义绑定器Binder作为中间层,实现了应用程序与消息中间件细节之间的隔离。

INPUT:消费者

OUTPUT:生产者

1.2.5 Stream中的消息通信方式遵循了发布-订阅模式

Topic主题进行广播

在RabbitMQ就是Exchange

在kafka中就是Topic

1.3 Spring Cloud Stream标准流程套路

image-20200822180539317

image-20200822180702228

  • Binder:连接中间件、屏蔽差异
  • Channel:通道,是队列Queue的一种抽象,在消息通讯系统中就是实现存储和转发的媒介,通过对Channel对队列进行配置
  • Source和Sink:简单的可理解为参照对象是Spring Cloud Stream自身,从Stream发布消息就是输出,接受消息就是输入
1.4 编码API和常用注解

image-20200822180940763

2、案例说明

RabbitMQ环境已经OK

工程中新建三个子模块:

  • cloud-stream-rabbitmq-provider8801,作为生产者进行发消息模块
  • cloud-stream-rabbitmq-consumer8802,作为消息接收模块
  • cloud-stream-rabbitmq-consumer8803,作为消息接收模块

3、消息驱动之生产者

3.1 新建model——cloud-stream-rabbitmq-provider8801
3.2 POM

新引进的pom

   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
   </dependency>
<dependencies>
        <!--stream-rabbit-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
3.3 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: # 这个名字是一个通道的名称
          destination: studyExchange # 表示要使用的Exchange名称定义
          content-type: application/json # 设置消息类型,本次为json,文本则设置“text/plain”
          binder: defaultRabbit  # 设置要绑定的消息服务的具体设置

eureka:
  client: # 客户端进行Eureka注册的配置
    service-url:
      defaultZone: http://localhost: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地址
3.4 业务类
3.4.1 发送消息接口
package com.atguigu.springcloud.service;

//消息发送者的接口
public interface IMessageProvider {
    public String send();
}
3.4.2 发送消息接口的实现类

新知识:

  • @EnableBinding(Source.class) //定义消息的推送广告
  • private MessageChannel output;//消息发送管道
  • MessageBuilder
package com.atguigu.springcloud.service.impl;
......
@EnableBinding(Source.class)  //定义消息的推送广告
public class MessageProviderImpl implements IMessageProvider {

    @Resource
    private MessageChannel output;//消息发送管道
    @Override
    public String send() {
        String serial = UUID.randomUUID().toString();
        output.send(MessageBuilder.withPayload(serial).build());
        System.out.println("*******serial: "+serial);
        return null;
    }
}
3.4.3 Conteoller
package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.service.IMessageProvider;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class MessageController {
    @Resource
    private IMessageProvider messageProvider;

    @GetMapping("/sendMessage")
    public String sendMessage(){
        return messageProvider.send();
    }
}
3.5 主启动类
package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StreamMQMain8801 {
    public static void main(String[] args) {
        SpringApplication.run(StreamMQMain8801.class,args);
    }
}
3.6 测试
  • 启动7001eureka

  • 启动rabbitmq

    • http://localhost:15672/
    • image-20200821103426876
  • 启动8801

  • 访问http://localhost:8801/sendMessage

后台打印:

image-20200821103541042

RabbitMQ显示:

image-20200821103639743

4、消息驱动之消费者

4.1 新建model——cloud-stream-rabbitmq-comsumer8802
4.2 POM

跟生产者一样

4.3 YML
server:
  port: 8802

spring:
  application:
    name: cloud-stream-comsumer  #微服务名称
  cloud:
    stream:
      binders: # 在此处配置要绑定的rabbitmq的服务信息;
        defaultRabbit: # 表示定义的名称,用于于binding整合
          type: rabbit # 消息组件类型
          environment: # 设置rabbitmq的相关的环境配置
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
      bindings: # 服务的整合处理
        input: # 这个名字是一个通道的名称
          destination: studyExchange # 表示要使用的Exchange名称定义
          content-type: application/json # 设置消息类型,本次为json,文本则设置“text/plain”
          binder: defaultRabbit  # 设置要绑定的消息服务的具体设置

eureka:
  client: # 客户端进行Eureka注册的配置
    service-url:
      defaultZone: http://localhost: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地址
4.4 业务类

controller

package com.atguigu.springcloud.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

@Component
@EnableBinding(Sink.class)
public class ReceiveMessageListenerController {
    @Value("${server.port}")
    private String serverPort;

    @StreamListener(Sink.INPUT)
    public void input(Message<String> message){
        System.out.println("消费者1号,------接收到的消息为:  "+message.getPayload()+"\t  port: "+serverPort);
    }
}
4.5 主启动类
package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

4.6 测试

启动:7001 、 8801 、 8802

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

结果:

  • 生产者8801:

    image-20200821172729875

  • 消费者8802

image-20200821172825934

  • RabbitMQ:

    image-20200821172139147

5、分组消费与持久化

5.1 依照8802,clone出来一份运行8803

cloud-stream-rabbitmq-consumer8803

5.2 启动
  • RabbitMQ
  • 7001 服务注册
  • 8801 消息生产
  • 8802 消息消费
  • 8803 消息消费

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

8801:

image-20200822155829484

8802:

image-20200822155902075

8803:

image-20200822155944120

5.3 运行后两个问题
  • 重复消费
  • 消息持久化
5.4 解决重复消费

目前是8802/8803同时都收到了,存在重复消费问题

如何解决:

分组和持久化属性group=

生产实际案例:

比如在如下场景中,订单系统我们做集群部署,都会从RabbitMQ中获取订单信息,
那如果一个订单同时被两个服务获取到,那么就会造成数据错误,我们得避免这种情况。
这时我们就可以使用Stream中的消息分组来解决

image-20200822162451984

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

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

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

首先来了解一下分组

5.5 分组
5.5.1 原理:

微服务应用放置于同一个group中,就能够保证消息只会被其中一个应用消费一次。不同的组是可以消费的,同一个组内会发生竞争关系,只有其中一个可以消费。

5.5.2 查看当前的group:

首先看一下,当前的group:

两个消费者的group:不一样

image-20200822164304840

所以属于不同的组,就会重复消费

5.5.3 将8802/8803都变成不同组,group两个不同

group: atguiguA、atguiguB

修改YML:

8802:group: atguiguA

8803:group: atguiguB

image-20200822164947015

5.5.4 结论:

还是重复消费

解决:

8802/8803实现了轮询分组,每次只有一个消费者 8801模块的发的消息只能被8802或8803其中一个接收到,这样避免了重复消费

8802/8803都变成相同组,group两个相同

都改成group:atguiguA

测试:8801访问2次

image-20200822165332125

查看8802:

image-20200822165352446

查看8803:

image-20200822165414137

同一个组的多个微服务实例,每次只会有一个拿到

所以解决了重复消费

5.6 解决消息持久化

通过上述,解决了重复消费问题,再看看持久化

停止8802/8803并去除掉8802的分组group:atguiguA,8803的分组group:atguiguA没有去掉

8801先发送4条信息到rabbitmq

image-20200822165838476

先启动8802,无分组属性配置,后台没有打出来消息

然后启动8803,有分组属性配置,后台打出来了MQ上的消息

image-20200822170046935

总结:要想在服务停止后也能接收到生产者发来的消息,就配置group属性

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值