Spring-Cloud-Stream & RocketMQ 简介及简单demo

Spring Cloud Stream 在 Spring Cloud 体系内用于构建高度可扩展的基于事件驱动的微服务,其目的是为了简化消息在 Spring Cloud 应用程序中的开发。

Spring Cloud Stream的核心构件是:

Destination Binders: 负责提供与外部消息系统集成的组件。
Destination Bindings: 作为消息中间件与应用程序的提供者和消费者之间的桥梁。
Message: 生产者和消费者用于与目的地装订器沟通的典型数据结构(从而通过外部消息系统与其他应用程序进行通信的典型数据结构)。
大概的意思就是我们以后就不用管消息中间件是啥了,这些都由spring-cloud-stream去管理。比如我们现在使用的是rabbitmq,后期项目要求换成rocketmq,我们不用去改代码。换个依赖,配置文件改一改就OK了。

如下图所示:

消息通过MessageChannel(output)发送(这里底层scs会怎样通过一系列调用将消息发送给mq我们都不用管)
mq收到消息后,中间件内部会有通道适配器,将中间件特有的消息格式转换为 SpringMessage,然后发送到
MessageChannel(input)
我们通过监听MessageChannel(input)就能拿到对应的消息进行消费了

上代码
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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.example</groupId>
    <artifactId>mq</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-test-support</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
配置文件application.yml

spring:
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: "127.0.0.1:9876"
      bindings:
        my-output:
          destination: topic1 #相当于RocketMQ中的topic
          content-type: application/json # 内容格式。这里使用 JSON
        my-input:
          destination: topic1 #相当于RocketMQ中的topic
          group:  group1 #消费组
          content-type: application/json # 内容格式。这里使用 JSON
          consumer:
            concurrency: 5 #实例数量
            broadcasting: false # 是否使用广播消费,默认为 false 使用集群消费,如果要使用广播消费值设成true。
        #集群消费:相同消费者下的实例平摊消息
        #广播消费:相同消费组下的每个实例都消费所有消息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
创建一个消息管道 MyChannel
创建完成之后记得在启动类上加注解 @EnableBinding({MyChannel.class}) 让启动类知道这个自定义消息管道

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.stereotype.Component;

@Component
public interface MyChannel {

    String OUTPUT = "my-output";
    String INPUT = "my-input";

    //声明了一个名字为my-output的Output Binding。注意,这个名字要和我们配置文件中的 spring.cloud.stream.bindings 配置项对应上。
    @Output(MyChannel.OUTPUT)
    MessageChannel output();

    //声明了一个名字为my-input的Output Binding。注意,这个名字要和我们配置文件中的 spring.cloud.stream.bindings 配置项对应上。
    @Input(MyChannel.INPUT)
    SubscribableChannel input();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
创建生产者

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @Autowired
    private MyChannel myChannel;

    @RequestMapping("/send")
    public void send(String message,String headerValue){
        Message<String> myMessage = MessageBuilder.withPayload(message)
                .setHeader("myheader",headerValue)
                .build();
        myChannel.output().send(myMessage);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
创建消费者

@Component
public class MyCustomer {

    //value指定监听的Channel condition实现多个监听者方法的选择调度
    @StreamListener(value = MyChannel.INPUT, condition = "headers['myheader']=='header1'")
    public void testCustomListener(Message<String> message) {
        System.out.println(message.getHeaders().get("myheader") + "||" + message.getPayload().toString());
    }

    @StreamListener(value = MyChannel.INPUT, condition = "headers['myheader']=='header2'")
    public void testCustomListener(@Payload String message) {
        //如果消息对象是引用类型,需要使用@Payload进行反序列化 这里String其实不用也可以
        System.out.println("header2||" + message);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
启动程序,发送一条消息


再发送一条消息 localhost:8080/send?message=消息1&headerValue=header2

可以看到@StreamListener注解中的condition限制了消费者去消费对应的消息。我理解和rocketmq中的tag差不多

解耦
通过集群消费的机制,我们可以实现针对相同 Topic ,不同消费者分组实现各自的业务逻辑。
比如说来了一个用户注册请求,主要业务是将新用户数据插入数据库。然后还有一些什么发邮箱给用户,发短信给用户,这些次要服务都是通过消息队列异步操作的,同时也实现了解耦,只需要干自己的事就行了。
scs可以使用相同 Topic ,不同消费者分组实现。
改造上面的demo
配置文件

spring:
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: "127.0.0.1:9876"
      bindings:
        my-output:
          destination: topic1 #相当于RocketMQ中的topic
          content-type: application/json # 内容格式。这里使用 JSON
        my-input:
          destination: topic1 #相当于RocketMQ中的topic
          group:  group1 #消费组
          content-type: application/json # 内容格式。这里使用 JSON
          consumer:
            concurrency: 5 #实例数量
            broadcasting: false # 是否使用广播消费,默认为 false 使用集群消费,如果要使用广播消费值设成true。
        #集群消费:相同消费者下的实例平摊消息
        #广播消费:相同消费组下的每个实例都消费所有消息
        mail-input:
          destination: topic1 #相当于RocketMQ中的topic
          group:  group2 #消费组
          content-type: application/json # 内容格式。这里使用 JSON
          consumer:
            concurrency: 5 #实例数量
            broadcasting: false # 是否使用广播消费,默认为 false 使用集群消费,如果要使用广播消费值设成true。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
新增一个channel

@Component
public interface MailChannel {

    String INPUT = "mail-input";

    @Input(MailChannel.INPUT)
    SubscribableChannel input();
}
1
2
3
4
5
6
7
8
新增一个消费者

@Component
public class MailCustomer {
    @StreamListener(value = MailChannel.INPUT, condition = "headers['myheader']=='header1'")
    public void testCustomListener(@Payload String message) {
        //如果消息对象是引用类型,需要使用@Payload进行反序列化 这里String其实不用也可以
        System.out.println("邮箱消费||" + message);
    }
}
1
2
3
4
5
6
7
8
生产一条消息

可以看到两个消费组都消费了该消息

————————————————
版权声明:本文为CSDN博主「南城.南城」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_49558851/article/details/115489785

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值