1.第一步
/** * 设置消息的失效时间 */
public class DelayMessagePostProcessor implements MessagePostProcessor {
private long ttl = 0L; public DelayMessagePostProcessor(long ttl) { this.ttl = ttl; } @Override public Message postProcessMessage(Message message) throws AmqpException { message.getMessageProperties().setExpiration(Long.toString(ttl)); return message; } }
2.第二步
/** * 设置消息的转化体 */
/** 消息发送队列 延迟缓冲(按消息) */ public static final String QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SEND = "delay:per:message:msg:send"; /** 消息发送队列 DLX */ public static final String DLX_MSG_SEND = "msg:send:dlx"; /** 消息发送 1.短信 2.站内信 **/ public static final String QUEUE_MSG_SEND = "msg:send";
/** * 短信发送队列 * @return */ @Bean public Queue msgQueueDelayPerMessageTTL() { return QueueBuilder.durable(QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SEND) .withArgument("x-dead-letter-exchange", DLX_MSG_SEND) .withArgument("x-dead-letter-routing-key", QUEUE_MSG_SEND) .build(); } /** * 延迟短信交换定义 * @return */ @Bean public DirectExchange msgDelayExchange(){ return new DirectExchange(DLX_MSG_SEND); } /** * 绑定 * @param msgQueue 消费队列 * @param msgDelayExchange DLX * @return */ @Bean public Binding smsDelayBinding(Queue msgQueue, DirectExchange msgDelayExchange) { return BindingBuilder.bind(msgQueue) .to(msgDelayExchange) .with(QUEUE_MSG_SEND); }
第三步
消息队列服务端消费
@Component @RabbitListener(queues = QUEUE_MSG_SEND) public class MsgReceiver { private Log log = LogFactory.getLog(MsgReceiver.class); @Resource private MsgService msgService; @Resource private MemberUserService memberUserService; private ObjectMapper mapper = new ObjectMapper(); @RabbitHandler public void process(Msg msg) { try { log.info("-----消息发送开始------"); log.info(mapper.writeValueAsString(msg)); msgService.sendMsg(msg); //短信发送 log.info("-----消息发送结束------"); } catch (Exception e) { log.error(e.getMessage(), e); } } }
第四步
生产者使用方法
Msg msg = new Msg(); msg.setMemberId("1"); msg.setType(17); amqpTemplate.convertAndSend(QUEUE_DELAY_PER_MESSAGE_TTL_MSG_SEND, msg, new DelayMessagePostProcessor(100)); System.out.println(UF.getFormatDateTime(UF.getDateTime()));