RocketMQ下载、安装、以及结合Springboot的使用
业务应用场景
消息队列的应用场景:主要用于处理高并发作削峰处理、业务解耦等,比如说 大规模的短信推送、订单抓取、库存同步、消息同步等。
下载
wget https://archive.apache.org/dist/rocketmq/4.5.1/rocketmq-all-4.5.1-bin-release.zip
安装
unzip rocketmq-all-4.5.1-bin-release.zip
启动
cd rocketmq-all-4.5.1-bin-release/bin
启动nameServer、并验证
nohup sh mqnamesrv &
tail -f ~/logs/rocketmqlogs/namesrv.log
# 如果成功启动,能看到类似如下的日志:
2019-07-18 17:03:56 INFO main - The Name Server boot success. ...
启动Broker 并验证 (如果启动失败,调整内存参数)
nohup sh mqbroker -n localhost:9876 autoCreateTopicEnable=true &
tail -f ~/logs/rocketmqlogs/broker.log
# 如果启动成功,能看到类似如下的日志:
2019-07-18 17:08:41 INFO main - The broker[itmuchcomdeMacBook-Pro.local, 192.168.43.197:10911] boot success. serializeType=JSON and name server is localhost:9876
关闭MQ
sh mqshutdown namesrv
注意
如果一直报错 172.17.0.11:10911 连接失败,需要新增ip配置文件并指定
brokerIP1=xxx
nohup sh mqbroker -n 172.17.0.11:9876 autoCreateTopicEnable=true -c conf/broker.conf &
实战
pom依赖
<dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
发送消息
@Resource private RocketMQTemplate rocketMQTemplate; @Value("${pet.topic.order}") private String orderTopic; @Scheduled(cron = "0 0 0 1/1 * ? ") public void send() { rocketMQTemplate.syncSendOrderly(orderTopic, "这是一条MQ消息", UUID.randomUUID().toString()); log.info("MQ发送消息成功"); }
接收消息
package agatha.pet.mq; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.stereotype.Component; /** * @author oak * @date 2021/1/11 */ @Slf4j @Component @RocketMQMessageListener(consumerGroup = "pet_group", topic = "${pet.topic.order}") public class OrderConsumer implements RocketMQListener<String> { @Override public void onMessage(String msg) { log.info("MQ.order.msg:{}", msg); } }