提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:以下是本篇文章参考学习的几个前辈的案例
https://blog.csdn.net/lvshunxiang/article/details/130419712
https://blog.csdn.net/Jason_2020/article/details/130189446
https://blog.csdn.net/weixin_43870997
一、spring-cloud-starter-stream 3.x版本和4.x版本最大区别?
3.x 版本的使用, 都是基本上都是通过注解
@EnableBinding
@Input
@Output
@StreamListener
等注解来实现对不同信道的绑定.
具体使用可参考: https://www.cnblogs.com/xfeiyun/p/16229303.html
4.x 完全删除了这些注解,使用的是一个Consumer类型的Bean来对消息队列进行消费,完全提倡函数式编程
具体可以去看看官网
二、使用
1、依赖的引入
官方对应项目示例只有前四个是官方在维护,后面则是非官方维护,rocketMQ是由阿里维护的
版本依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>
2、生产者配置
代码如下(实例):
@RestController
@RequestMapping("/corp")
public class TestController {
@Autowired
private StreamBridge streamBridge;
@GetMapping("/im")
public String im() {
String uuid = UUID.fastUUID().toString();
streamBridge.send("im-out", "im-out-"+uuid);
return "success";
}
yarm
spring:
application:
# 对应config server所获取的配置文件的 {application}
name: xxxxxx
cloud:
stream:
bindings:
# 消息生产者
im-out:
destination: 'im-group-topic'
content-type: application/json
group: 'im-group'
binder: rocketmq
rocketmq:
binder:
name-server: localhost:9876
group: im-group
注册成功后,在rocketMQ的web显示上会有一个对应的主题显示
也有说必须严格要求,但我试了一下,生产者不严格要求也可以实现。详见https://blog.csdn.net/weixin_43870997/article/details/133411836
有条件的也可去研究一下对应源码
3、消费者配置
代码如下(实例):
@Slf4j
@Configuration
public class RecStrConsumer {
@Bean
public Function<String,String> toUpperCase() {
return String::toUpperCase;
}
//创建消费者
@Bean
public Consumer<String> im() {
return str -> {
log.info("接收字符串,im-group-topic,---" + str);
};
}
}
@Slf4j
@Configuration
public class RecStr2Consumer {
@Bean
public Consumer<String> custom() {
return str -> {
log.info("接收字符串,im-group-topic2,---" + str);
};
}
}
yarm
cloud:
function:
definition: toUpperCase|im;custom
stream:
bindings:
toUpperCaseim-in-0:
destination: 'im-group-topic'
content-type: application/json
group: 'im-group'
binder: rocketmq
custom-in-0:
destination: 'im-group-topic'
content-type: application/json
group: 'dead'
binder: rocketmq
注意: 多个方法之间可以使用 “|” 间隔, 但是绑定时 多个需要按顺序写.多个消费者之间使用;间隔
其中 -in-0 是一种约定,
不带-in-0产生的订阅组为
destination是消费者和生产者对应的参数
4、验证
总结
基本配置大概就是这些,当一个服务既作为消费者也作为生产者时的权宜之计,我也不确定自己的用法是否正确规范, 如果有大佬有标准的使用方式, 请及时评论, 感谢!