前言
RocketMQ
是一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务
环境
win10 + Spring Cloud Hoxton.SR9 + Spring Cloud Alibaba 2.2.6.RELEASE + RocketMQ 4.7.0
搭建搭建
关于
MQ
与
RocketMQ
的环境搭建查看之前的文章
具体实现
编写生产者(内容中心)
代码
-
pom.xml
<!-- rocketmq -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
-
application.yml
rocketmq:
name-server: 127.0.0.1:9876
producer:
group: producer-group
-
TestRocketController.java
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rocketmq")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestRocketController {
private final RocketMQTemplate rocketMQTemplate;
@PostMapping("test")
public String test() {
rocketMQTemplate.convertAndSend(
"test-msg",
"突然活得潦草了。。。");
return "success";
}
}
测试
- 访问接口
-
RocketMQ
控制台查看
http://localhost:8088/#/message
- 消息详情
编写消费者(用户中心)
代码
-
pom.xml
<!-- rocketmq -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
-
application.yml
rocketmq:
name-server: 127.0.0.1:9876
-
TestRocketConsumer.java
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RocketMQMessageListener(consumerGroup = "consumer-group", topic = "test-msg")
public class TestRocketConsumer implements RocketMQListener<String> {
@Override
public void onMessage(String str) {
// TODO 业务处理
log.info("监听到主题为'test-msg'的消息:" + str);
}
}
测试
- 重启应用
- 控制台消费记录
项目源码
-
GitHub
:
https://github.com/Maggieq8324/coisini-cloud-alibaba
-
Gitee
:
https://gitee.com/maggieq8324/coisini-cloud-alibaba
– End –
– 个人学习笔记 –
– 仅供参考 –