今天学习了springboot整合了RocketMQ。
首先导入相应坐标:
<dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.2.1</version> </dependency>
接下来做相应的配置:
rocketmq: name-server: localhost:9876 producer: group: group_rocketmq # 不写报错,配置生产者所在的组
接下来是实现:
@Service public class MessageServiceRocketmqImpl implements MessageService { @Autowired private RocketMQTemplate rocketMQTemplate; @Override public void sendMessage(String id) { System.out.println("待发送短信的订单已纳入处理队列(rocketmq),id: " + id); //rocketMQTemplate.convertAndSend("order_id",id); //同步消息 SendCallback callback = new SendCallback() { @Override public void onSuccess(SendResult sendResult) { System.out.println("消息发送成功"); } @Override public void onException(Throwable throwable) { System.out.println("消息发送失败"); } }; rocketMQTemplate.asyncSend("order_id",id,callback); //异步消息 } @Override public String doMessage() { return null; } }
//对应监听
@Component @RocketMQMessageListener(topic = "order_id",consumerGroup = "group_rocketmq") //第一个参数写入队列的名字,第二个参数写入分组在application.yml配置rocketmq中的group属性,使生产者和消费者在一个组中 public class MessageListener implements RocketMQListener<String> { @Override public void onMessage(String id) { System.out.println("已完成短信发送业务(rocketmq),id: " + id); } }
欢迎大家一起来学习,有不足的地方还请指出。