和发送同步消息一样,只不过消息要设置下延迟时间级别
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;
/**
* 发送延迟消息
*/
public class Producer {
public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
DefaultMQProducer producer = new DefaultMQProducer("delayGroup");
producer.setNamesrvAddr("192.168.197.126:9876;192.168.197.123:9876");
producer.start();
for (int i = 0; i < 10; i++) {
Message message = new Message("delayTopic","tag",("delayMessage"+i).getBytes());
//设置消息延迟级别 messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
message.setDelayTimeLevel(2);
SendResult sendResult = producer.send(message);
System.out.println(sendResult);
}
producer.shutdown();
}
}