rocketmq 延时消息
rocketmq支持为消息设置延时时间,预设的时间长度为
1s、5s、10s、30s;
1m、2m、 3m、4m、5m、6m、7m、8m、9m、10m、20m、30m;
1h,2h
通过message类中设置消息的延时级别
public class Message implements Serializable {
public int getDelayTimeLevel() {
String t = this.getProperty("DELAY");
return t != null ? Integer.parseInt(t) : 0;
}
public void setDelayTimeLevel(int level) {
this.putProperty("DELAY", String.valueOf(level));
}
。。。。
}
******************************************
使用示例
******************************************
producer 端
@Service
public class ProducerService {
@Value("${rocketmq.producerGroup}")
private String producerGroup;
@Value("${rocketmq.namesrv}")
private String namesrv;
private DefaultMQProducer producer;
@PostConstruct
public void initDefaultMQProducer(){
producer=new DefaultMQProducer(producerGroup);
producer.setNamesrvAddr(namesrv);
producer.setRetryTimesWhenSendFailed(2);
try{
producer.start();
}catch (Exception e){
e.printStackTrace();
}
}
public void sendDelay(){
try{
Message message=new Message("topic","delay",("瓜田李下 延时发送 "+System.currentTimeMillis()).getBytes());
message.setDelayTimeLevel(2);
SendResult result=producer.send(message);
}catch (Exception e){
e.printStackTrace();
}
}
@PreDestroy
public void destroy(){
if(producer!=null){
producer.shutdown();
}
}
}
***************************************
consumer 端
@Service
public class ConsumerService {
@Value("${rocketmq.consumerGroup}")
private String consumerGroup;
@Value("${rocketmq.namesrv}")
private String namesrv;
@PostConstruct
public void consumeSync(){
DefaultMQPushConsumer consumer=new DefaultMQPushConsumer(consumerGroup);
consumer.setNamesrvAddr(namesrv);
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
try{
Thread.sleep(2000);
consumer.subscribe("topic","*");
consumer.registerMessageListener((MessageListenerConcurrently) (list, consumeConcurrentlyContext) -> {
try{
for(MessageExt messageExt:list){
String body=new String(messageExt.getBody());
System.out.println(body);
System.out.println("消费时间:"+System.currentTimeMillis());
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
System.out.println("消费失败");
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
});
}catch (Exception e){
e.printStackTrace();
}
try{
consumer.start();
}catch (Exception e){
e.printStackTrace();
}
}
}
****************************************
控制台输出