控制消息侦听器容器停止一段时间并再次开始侦听

时间:2017-03-21 11:30:58

标签: java spring spring-jms jmstemplate

听众:

 <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>

我想停止容器监听JMS消息并在一段时间后再次启动它?

可以实现吗?

1 个答案:

答案 0 :(得分:0)

也许有更好的解决方案,但我认为这个可以适合:

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