delay delivery of message in activeMQ in spring bo

2019-09-20 17:35发布

问题:

I want to send a message at any time 't' that will be received by the receiver after 'x' sec.

for doing so, I have written sender code

@Autowired
private JmsTemplate jmsTemplate;
private Queue queue = new ActiveMQQueue("topicName");

public void show(String message) {
    try {
        System.out.println("Sending message " + message);
        jmsTemplate.convertAndSend(queue, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws JMSException {
                System.out.println("postProcessMessage executed ");
                message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 3 * 60 * 1000);
                System.out.println("long time " + message
                        .getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY));
                return message;
            }
        });
        System.out.println("Sending done " + message + " at " + System.currentTimeMillis());
    } catch (Exception er) {
        er.printStackTrace();
    }
}

and Reciever code

@JmsListener(destination = "topicName")
    public void reciever(String message) {
        System.out.println("receiving message " + message + " at " + System.currentTimeMillis());
    }

But message received by receiver instant .without any delay.

output is

Sending message this is a message
postProcessMessage executed long time 180000
receiving message this is a message at 1514391984964
Sending done this is a message at 1514391984970

configuration file is

@Bean
    JmsTemplate createJMSTemplate(ConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(connectionFactory);
        return jmsTemplate;
    }

    @Bean
    ConnectionFactory myActiveMQConnectionFactory() {
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setBackOffMultiplier(1);
        redeliveryPolicy.setUseExponentialBackOff(false);
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        connectionFactory.setRedeliveryPolicy(redeliveryPolicy);
        NetworkConnector networkConnector = new DiscoveryNetworkConnector();
        networkConnector.setConsumerTTL(2);

        return connectionFactory;
    }

回答1:

Delayed message is not supported by activemq with default config, you should turn it on at first.

adding schedulerSupport in activemq.conf

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" schedulerSupport="true">