• Spring Cloud Stream消息驱动组件


            Spring Cloud Stream 消息驱动组件帮助我们更快速,更方便,更友好的去构建消息驱动微服务的。当时定时任务和消息驱动的⼀个对比。(消息驱动:基于消息机制做一些事情)

    MQ:消息队列/消息中间件/消息代理,产品有很多,ActiveMQ RabbitMQ RocketMQ Kafka

    1、Stream解决的痛点问题

            MQ消息中间件广泛应用在应用解耦合、异步消息处理、流量削峰等场景中。

            不同的MQ消息中间件内部机制包括使用方式都会有所不同,比如RabbitMQ中有Exchange(交换机/交换器)这一概念,kafka有Topic、Partition分区这些概念,MQ消息中间件的差异性不利于我们上层的开发应用,当我们的系统希望从原有的RabbitMQ切换到Kafka时,我们会发现比较困难,很多要操作可能重来(因为应用程序和具体的某⼀款MQ消息中间件耦合在⼀起了)。

            Spring Cloud Stream进行了很好的上层抽象,可以让我们与具体消息中间件解耦合,屏蔽掉了底层具体MQ消息中间件的细节差异,就像Hibernate屏蔽掉了具体数据库(Mysql/Oracle一样)。如此⼀来,我们学习、开发、维护MQ都会变得轻松。目前Spring Cloud Stream支持RabbitMQ和Kafka。

    本质:屏蔽掉了底层不同MQ消息中间件之间的差异,统一了MQ的编程模型,降低了学习、开发、维护MQ的成本

    2、Stream重要概念

            Spring Cloud Stream 是⼀个构建消息驱动微服务的框架。应用程序通过inputs(相当于消息消费者consumer)或者outputs(相当于消息生产者producer)来与Spring Cloud Stream中的binder对象交互,而Binder对象是用来屏蔽底层MQ细节的,它负责与具体的消息中间件交互。

    说白了:对于我们来说,只需要知道如何使⽤Spring Cloud Stream与Binder对象交互即可

    Binder绑定器  

            Binder绑定器是Spring Cloud Stream 中非常核心的概念,就是通过它来屏蔽底层不同MQ消息中间件的细节差异,当需要更换为其他消息中间件时,我们需要做的就是更换对应的Binder绑定器而不需要修改任何应用逻辑(Binder绑定器的实现是框架内置的,Spring Cloud Stream目前支持Rabbit、Kafka两种消息队列) 

    3、传统MQ模型与Stream消息驱动模型

    4、Stream消息通信方式及编程模型 

    4.1、Stream消息通信方式

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

            在Spring Cloud Stream中的消息通信方式遵循了发布-订阅模式,当一条消息被投递到消息中间件之 后,它会通过共享的 Topic 主题进行广播,消息消费者在订阅的主题中收到它并触发自身的业务逻辑处理。这里所提到的 Topic 主题是SpringCloud Stream中的一个抽象概念,用来代表发布共享消息给消 费者的地方。在不同的消息中间件中, Topic 可能对应着不同的概念,比如:在RabbitMQ中的它对应了Exchange、在Kakfa中则对应了Kafka中的Topic。

    4.2、Stream编程注解

            如下的注解无非在做一件事,把我们结构图中那些组成部分上下关联起来,打通通道(这样的话生产者的message数据才能进入mq,mq中数据才能进入消费者工程)。

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

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

    (1)在lagou_parent下新建子module:lagou-cloud-stream-producer-9090

    (2)pom.xml中添加依赖

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <parent>
    6. <artifactId>lagou-parentartifactId>
    7. <groupId>com.lagou.edugroupId>
    8. <version>1.0-SNAPSHOTversion>
    9. parent>
    10. <modelVersion>4.0.0modelVersion>
    11. <artifactId>lagou-cloud-stream-producer-9090artifactId>
    12. <dependencies>
    13. <dependency>
    14. <groupId>org.springframework.cloudgroupId>
    15. <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframework.cloudgroupId>
    19. <artifactId>spring-cloud-starter-stream-rabbitartifactId>
    20. dependency>
    21. dependencies>
    22. project>

    (3)application.yml添加配置

    1. server:
    2. port: 9090
    3. spring:
    4. application:
    5. name: lagou-cloud-stream-producer
    6. cloud:
    7. stream:
    8. binders: # 绑定MQ服务信息(此处我们是RabbitMQ)
    9. lagouRabbitBinder: # 给Binder定义的名称,用于后面的关联
    10. type: rabbit # MQ类型,如果是Kafka的话,此处配置kafka
    11. environment: # MQ环境配置(用户名、密码等)
    12. spring:
    13. rabbitmq:
    14. host: localhost
    15. port: 5672
    16. username: guest
    17. password: guest
    18. bindings: # 关联整合通道和binder对象
    19. output: # output是我们定义的通道名称,此处不能乱改
    20. destination: lagouExchange # 要使用的Exchange名称(消息队列主题名称)
    21. content-type: text/plain # application/json # 消息类型设置,比如json
    22. binder: lagouRabbitBinder # 关联MQ服务
    23. eureka:
    24. client:
    25. serviceUrl: # eureka server的路径
    26. defaultZone: http://lagoucloudeurekaservera:8761/eureka/,http://lagoucloudeurekaserverb:8762/eureka/ #把 eureka 集群中的所有 url 都填写了进来,也可以只写一台,因为各个 eureka server 可以同步注册表
    27. instance:
    28. prefer-ip-address: true #使用ip注册

    (4)启动类

    1. package com.lagou.edu;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    5. @SpringBootApplication
    6. @EnableDiscoveryClient
    7. public class StreamProducerApplication9090 {
    8. public static void main(String[] args) {
    9. SpringApplication.run(StreamProducerApplication9090.class, args);
    10. }
    11. }

    (5)业务类开发(发送消息接口、接口实现类)

    接口

    1. package com.lagou.edu.service;
    2. public interface IMessageProducer {
    3. public void sendMessage(String content);
    4. }

    实现类

    1. package com.lagou.edu.service.impl;
    2. import com.lagou.edu.service.IMessageProducer;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.cloud.stream.annotation.EnableBinding;
    5. import org.springframework.cloud.stream.messaging.Source;
    6. import org.springframework.messaging.support.MessageBuilder;
    7. // Source.class里面就是对输出通道的定义(这是Spring Cloud Stream内置的通道封装)
    8. @EnableBinding(Source.class)
    9. public class MessageProducerImpl implements IMessageProducer {
    10. // 将MessageChannel的封装对象Source注入到这里使用
    11. @Autowired
    12. private Source source;
    13. @Override
    14. public void sendMessage(String content) {
    15. // 向mq中发送消息(并不是直接操作mq,应该操作的是spring cloud stream)
    16. // 使用通道向外发出消息(指的是Source里面的output通道)
    17. source.output().send(MessageBuilder.withPayload(content).build());
    18. }
    19. }

    测试类

    1. import com.lagou.edu.StreamProducerApplication9090;
    2. import com.lagou.edu.service.IMessageProducer;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    8. @SpringBootTest(classes = {StreamProducerApplication9090.class})
    9. @RunWith(SpringJUnit4ClassRunner.class)
    10. public class MessageProducerTest {
    11. @Autowired
    12. private IMessageProducer iMessageProducer;
    13. @Test
    14. public void testSendMessage() {
    15. iMessageProducer.sendMessage("hello world-lagou101");
    16. }
    17. }

    4.4、Stream消息驱动之开发消费者端

    注:消费端引入的jar与服务端引入的jar包相同,故省略。

    (1)application.yml

    1. server:
    2. port: 9091
    3. spring:
    4. application:
    5. name: lagou-cloud-stream-consumer
    6. cloud:
    7. stream:
    8. binders: # 绑定MQ服务信息(此处我们是RabbitMQ)
    9. lagouRabbitBinder: # 给Binder定义的名称,用于后面的关联
    10. type: rabbit # MQ类型,如果是Kafka的话,此处配置kafka
    11. environment: # MQ环境配置(用户名、密码等)
    12. spring:
    13. rabbitmq:
    14. host: localhost
    15. port: 5672
    16. username: guest
    17. password: guest
    18. bindings: # 关联整合通道和binder对象
    19. input: # input是我们定义的通道名称,此处不能乱改
    20. destination: lagouExchange # 要使用的Exchange名称(消息队列主题名称)
    21. content-type: text/plain # application/json # 消息类型设置,比如json
    22. binder: lagouRabbitBinder # 关联MQ服务
    23. group: lagou001 # 分组
    24. eureka:
    25. client:
    26. serviceUrl: # eureka server的路径
    27. defaultZone: http://lagoucloudeurekaservera:8761/eureka/,http://lagoucloudeurekaserverb:8762/eureka/ #把 eureka 集群中的所有 url 都填写了进来,也可以只写一台,因为各个 eureka server 可以同步注册表
    28. instance:
    29. prefer-ip-address: true #使用ip注册

    (2)消息消费者监听类

    1. package com.lagou.edu.service;
    2. import org.springframework.cloud.stream.annotation.EnableBinding;
    3. import org.springframework.cloud.stream.annotation.StreamListener;
    4. import org.springframework.cloud.stream.messaging.Sink;
    5. import org.springframework.messaging.Message;
    6. @EnableBinding(Sink.class)
    7. public class MessageConsumerService {
    8. @StreamListener(Sink.INPUT)
    9. public void recevieMessages(Message message) {
    10. System.out.println("=========接收到的消息:" + message);
    11. }
    12. }

    (3)启动类

    1. package com.lagou.edu;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    5. @SpringBootApplication
    6. @EnableDiscoveryClient
    7. public class StreamConsumerApplication9091 {
    8. public static void main(String[] args) {
    9. SpringApplication.run(StreamConsumerApplication9091.class,args);
    10. }
    11. }

    至此,消费端与服务端代码编写完成。

    5、Stream高级之自定义消息通道

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

            我们是可以自定义消息通道的,学着SourceSink的样子,给你的通道定义个自己的名字,多个输入通道和输出通道是可以写在一个类中的。

    定义接口

    1. interface CustomChannel {
    2. String INPUT_LOG = "inputLog";
    3. String OUTPUT_LOG = "outputLog";
    4. @Input(INPUT_LOG)
    5. SubscribableChannel inputLog();
    6. @Output(OUTPUT_LOG)
    7. MessageChannel outputLog();
    8. }

    如何使用?

    1. @EnableBinding 注解中,绑定自定义的接口
    2. 使用 @StreamListener 做监听的时候,需要指定 CustomChannel.INPUT_LOG

    bindings:
            inputLog:
                    destination: lagouExchange
            outputLog:
                    destination: eduExchange

    6、Stream高级之消息分组 

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

    解决的问题:能解决消息重复消费问题

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

  • 相关阅读:
    SQLAlchemy使用教程
    计算机网络——物理层-物理层的基本概念、物理层下面的传输媒体
    fatal: not in a git directory Error: Command failed with exit 128: git
    论文阅读-Detecting and Recovering Sequential DeepFake Manipulation(SeqFakeFormer)
    ubuntu安装lua
    【每日前端面经】2024-03-10
    计算机学院2022级新生邀请赛(一)
    基于Multisim的LC正弦波振荡器的设计与仿真
    无旋Treap——FHQ Treap
    波奇学C++:哈希
  • 原文地址:https://blog.csdn.net/weixin_52851967/article/details/126580536