首先,引入rocketmq的依赖:
<!--rocketmq-->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
1 发送消息
package cn.jack.mq;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
public class RocketMQSendMessageTest {
public static void main(String[] args) throws Exception {
// TODO 1 创建消息生产者,指定生成组名
DefaultMQProducer defaultMQProducer = new DefaultMQProducer("jack-producer-group");
// TODO 2 指定NameServer的地址
defaultMQProducer.setNamesrvAddr("192.168.232.129:9876");
// TODO 3 启动生产者
defaultMQProducer.start();
// TODO 4 构建消息对象,主要是设置消息的主题、标签、内容
Message message = new Message("jack-topic", "jack-tag", ("测试消息发送 --Jack").getBytes());
// TODO 5 发送消息
SendResult result = defaultMQProducer.send(message);
System.out.println("SendResult-->" + result);
// TODO 6 关闭生产者
defaultMQProducer.shutdown();
}
}
2 接收消息
package cn.jack.mq;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
public class RocketMQReceiveMessageTest {
public static void main(String[] args) throws Exception {
// TODO 1 创建消费者,指定所属的消费者组名
DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("jack-consumer-group");
// TODO 2 指定NameServer的地址
defaultMQPushConsumer.setNamesrvAddr("192.168.232.129:9876");
// TODO 3 指定消费者订阅的主题和标签
defaultMQPushConsumer.subscribe("jack-topic", "*");
// TODO 4 进行订阅:注册回调函数,编写处理消息的逻辑
defaultMQPushConsumer.registerMessageListener((List<MessageExt> list, ConsumeConcurrentlyContext context) -> {
// 1 try catch(throwable)确保不会因为业务逻辑的异常,导致消息出现重复消费的现象
// 2 org.apache.rocketmq.client.impl.consumer.ConsumeMessageConcurrentlyService.ConsumeRequest.run()中会对Throwable进行捕获,
// 并且返回ConsumeConcurrentlyStatus.RECONSUME_LATER
try {
System.out.println("收到消息--》" + list);
// 模拟业务异常
int i = 1 / 0;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
// TODO 5 启动消费者
defaultMQPushConsumer.start();
System.out.println("消费者启动成功。。。");
}
}
rocketmq客户端日志文件的位置:${user.home}/logs/rocketmqlogs/