Producer消息延迟投递和定时投递(Delay and Schedule Message Delivery)
我们只需要把几个描述消息定时调度方式的参数作为属性添加到消息,broker端的调度器就会按照我们想要的行为去处理消息。
一共有4个属性
1:AMQ_SCHEDULED_DELAY :延迟投递的时间
2:AMQ_SCHEDULED_PERIOD :重复投递的时间间隔
3:AMQ_SCHEDULED_REPEAT:重复投递次数
4:AMQ_SCHEDULED_CRON:Cron表达式
需要在activemq.xml配置文件中配置schedulerSupport属性为true
<broker xmlns="http://activemq.apache.org/schema/core" schedulerSupport="true" brokerName="localhost" dataDirectory="${activemq.data}">
在Produer的发送消息之前设置延迟60s发送
TextMessage textMessage = session.createTextMessage("发送延迟消息" + i); //延迟60s发送 long time = 60 * 1000; textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); messageProducer.send(textMessage); System.out.println("发送延迟消息" + i);
延迟30s,间隔10s,发送10次
//延迟30s,间隔10s,发送10次
long delay = 30 * 1000;
long period = 10 * 1000;
int repeat = 9;
textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
messageProducer.send(textMessage); System.out.println("发送延迟消息" + i);
cron表达式发送:
每个整点发送一次
textMessage.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "0 * * * *");
cron表达式参考:https://blog.csdn.net/current_person/article/details/52799687