Spring中使用RocketMq收发消息,简单记录一下后面熟练使用了再完善一下内容。
1.依赖:
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<!--版本 https://mvnrepository.com 上对应一下-->
<version>2.1.0</version>
</dependency>
2.发送消息
@Component
public class UserInfoProvider {
@Resource
private RocketMQTemplate rocketMQTemplate;
//同步消息
public void sendSyncMessage(String message) {
SendResult sendResult = rocketMQTemplate.syncSend("boot:", message);
log.info("send message body={},result={}", message, sendResult.getSendStatus());
}
//异步消息
public void SendAsyncMessage() {
List list = new ArrayList();
list.add("异步消息发送");
rocketMQTemplate.asyncSend("boot", list, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
//成功回调
System.out.println(sendResult.getSendStatus());
}
@Override
public void onException(Throwable e) {
//异常回调
System.out.println(e.getMessage());
}
});
}
}
3.消费消息
@Component
@RocketMQMessageListener(
//topic主题
topic = "boot",
//consumerGroup消费者组
consumerGroup = "pm-service"
)
public class UserInfoConsume implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
@Override
public void onMessage(MessageExt messageExt) {
System.out.println("hello消费消息"+new String(messageExt.getBody()));
}
@Override
public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
//时间间隔
defaultMQPushConsumer.setPullInterval(2000);
// 设置每次从队列中拉取的消息数为16
defaultMQPushConsumer.setPullBatchSize(16);
}
}