1.代码

(1)生产者

package com.mq.rocket.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

public class DelayProducer {
public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
// 1.创建消息生产者producer,并指定生产者组名
DefaultMQProducer producer = new DefaultMQProducer("group1");
// 2.指定Nameserver地址
producer.setNamesrvAddr("127.0.0.1:9876");
producer.setSendMsgTimeout(5000);
// 3.启动producer
producer.start();
for (int i = 0; i < 10; i++) {
// 4.创建消息对象,指定主题Topic、Tag和消息体
/**
* 参数说明:
* 参数一:消息主题Topic
* 参数二:消息Tag
* 参数三:消息内容
*/
Message msg = new Message("DELAY_TOPIC", "*", ("Hello RocketMQ"+i).getBytes());
// 设置延迟时间
msg.setDelayTimeLevel(2);
// 5.发送消息
SendResult result = producer.send(msg);
System.out.println("发送结果:" + result);
TimeUnit.SECONDS.sleep(1); // 线程睡1秒
}

// 6.关闭生产者producer
producer.shutdown();
}
}

(2)消费者

package com.mq.rocket.delay;

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.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
* 消息接收者
*/
public class DelayConsumer {
public static void main(String[] args) throws MQClientException {
// 1.创建消费者consumer,指定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
// 2.指定Nameserver地址
consumer.setNamesrvAddr("127.0.0.1:9876");
// 设置超时
consumer.setConsumeTimeout(5000);
// 3.订阅主题topic和tag
consumer.subscribe("DELAY_TOPIC", "*");
// 4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently() {
// 接收消息内容
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
for (MessageExt msg:msgList) {
System.out.println("延迟消息:" + new String(msg.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
// 5.启动消费者consumer
consumer.start();
}
}

2.执行

RocketMQ延迟消息_java

RocketMQ延迟消息_延迟时间_02