SpringCloud Stream集成Rocketmq
首先需要引入依赖包
项目使用gradle进行构建依赖包如下:
//spring cloud stream
compile('com.alibaba.cloud:spring-cloud-starter-stream-rocketmq:2.2.1.RELEASE')
application.properties配置如下
#rocketmq服务地址,集群多台用';'分隔
spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
#生产者
#指定生产者发送的topic名称
spring.cloud.stream.bindings.ccAdminServiceMessageOut.destination=comment-topic-comment-insert
#指定编码类型
spring.cloud.stream.bindings.ccAdminServiceMessageOut.content-type=application/json
#消费者
#指定消费的topic名称
spring.cloud.stream.bindings.ccAdminServiceCommentIn.destination=comment-topic-comment-insert
#指定编码类型
spring.cloud.stream.bindings.ccAdminServiceCommentIn.content-type=application/json
#指定分组名称
spring.cloud.stream.bindings.ccAdminServiceCommentIn.group=cc-admin-comment-consumer-group
其中ccAdminServiceCommentIn与ccAdminServiceMessageOut为消费者与生产者对应的通道名称,这里通道名称不等同于topic名
public interface MessageProcessor {
String INPUT_CC_ADMIN_COMMENT_MESSAGE = "ccAdminServiceCommentIn";
String OUTPUT_CC_ADMIN_SERVICE_MESSAGE = "ccAdminServiceCommentOut";
@Input(INPUT_CC_ADMIN_COMMENT_MESSAGE)
SubscribableChannel inputBiServiceSoCreate();
@Output(OUTPUT_CC_ADMIN_SERVICE_MESSAGE)
MessageChannel ouputCcAdminServiceMsgOut();
}
@Input注解绑定了一个名为ccAdminServiceCommentIn的通道,对应的由消费者去使用
@Output注解绑定了一个名为ccAdminServiceCommentOut的通道,对应的由消息生产者去使用
下面是消费者的代码实现:
@EnableBinding({MessageProcessor.class})
@Slf4j
public class OrderMqReceive {
@StreamListener(MessageProcessor.INPUT_CC_ADMIN_COMMENT_MESSAGE)
public void messageListener(CommentMessageVo message) {
log.info("----> 监听到的comment信息:{}", message);
}
}
@EnableBinding:该注解用来指定一个或多个定义了@Input或@Output注解的接口,以此实现对消息通道(Channel)的绑定
@StreamListener:该注解主要定义在方法上,作用是将被修饰的方法注册为消息中间件上数据流的事件监听器,注解中的属性值对应了监听的消息通道名
生产者代码实现:
@EnableBinding({MessageProcessor.class})
@RestController
@Slf4j
public class CommentApiController {
@PostMapping(name = "发送队列消息", value = "/comment/sendMsg")
public ResponseBaseVo sendMq(@Valid @RequestBody QueryCommentListRequestVo queryCommentListRequestVo) {
Message message = MessageBuilder.withPayload(queryCommentListRequestVo).build();
messageProcessor.ouputCcAdminServiceMsgOut().send(message);
return ResponseBaseVo.ok();
}
}
本文介绍了如何在SpringCloud Stream中集成RocketMQ,包括引入依赖、配置application.properties、设置消费者和生产者的通道名称,并提供了消费者和生产者的代码实现。
2460

被折叠的 条评论
为什么被折叠?



