Control message listener container to stop for cer

2019-03-03 12:59发布

问题:

Listener :

 <bean id="msglistenerForAuditEvent" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsFactory"/>
        <property name="sessionTransacted" value="true"/>
        <property name="destinationName" value="test.event"/>
        <property name="messageListener" ref="auditListener" />
    </bean>

I want to stop the container to listen the JMS messages and start it again after certain period?

Can it be acheived?

回答1:

maybe there is better solution but i think this one can fit :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {

    @Autowired
    private DefaultMessageListenerContainer dmlc;

    @Scheduled(fixedDelay = 5000)
    public void start() {
        if (!dmlc.isRunning()) {
            dmlc.start();
        }
    }

    @Scheduled(fixedDelay = 5000)
    public void stop() {
        if (dmlc.isRunning()) {
            dmlc.stop();
        }
    }

    // @Scheduled(fixedDelay = 5000)
    // public void startOrStop() {
    // if (dmlc.isRunning()) {
    // dmlc.stop();
    // } else {
    // dmlc.start();
    // }
    // }

    @Bean
    public DefaultMessageListenerContainer dmlc() {
        DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
        // dmlc.set...
        return dmlc;
    }
}

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html