activemq发送延迟消息的工具类

1.demo

package com.util;

import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.io.Serializable;

@Component
public class MqProducerUtil {
     
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 延时发送
     *
     * @param name      发送的队列
     * @param data      发送的消息
     * @param delayTime 延迟时间 (单位秒)
     */
    public <T extends Serializable> void delaySend(String name, T data, int delayTime) {
     
        delaySend(name, data, delayTime, 1, 1);
    }

    /**
     * 延时发送
     *
     * @param name       发送的队列
     * @param data       发送的消息
     * @param delayTime  延迟时间 (单位秒)
     * @param repeatTime 重复投递间隔 (单位秒)
     * @param repeatNum  重复投递次数
     */
    public <T extends Serializable> void delaySend(String name, T data, int delayTime, int repeatTime, int repeatNum) {
     
        Destination destination = new ActiveMQQueue(name);
        // 获取连接工厂
        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        try (Connection connection = connectionFactory.createConnection();
             // 获取session,true开启事务,false关闭事务
             Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
             // 创建一个消息队列
             MessageProducer producer = session.createProducer(destination);
        ) {
     
            connection.start();
            producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
            ObjectMessage message = session.createObjectMessage(data);
            //设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delayTime * 1000L);//设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, repeatTime * 1000L);//设置重复投递间隔(非必要,根据实际情况)
            message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeatNum);//重复投递次数(非必要,根据实际情况)
            // 发送消息
            producer.send(message);
            session.commit();
            logger.info("name:[{}],data:[{}]", name, data);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }
}

2.文章参考链接
a.https://blog.csdn.net/wanghao112956/article/details/103042773
b.https://www.cnblogs.com/yjmyzz/p/active-mq-delay-and-schedule-message-delivery.html

你可能感兴趣的:(工具类,java)