启动和停止@JmsListener

时间:2016-03-31 12:02:13

标签: spring-boot spring-jms

我正在使用spring boot并拥有@EnableJms

如果我只使用注释@JmsListener(destination = "xxxxxx")并依赖于spring boot autoconfiguration,我如何启动和停止jmslistener知道我将其设置为自动启动false

 jms:
    listener:
      max-concurrency: 10
      concurrency: 1
      auto-startup: false

问题是如何访问SimpleMessageListenerContainerDefaultMessageListenerContainer

1 个答案:

答案 0 :(得分:2)

请参阅this answer - 可通过注册表访问各个容器,也可以启动/停止注册表以启动/停止所有容器。

修改

这是一个错误,我打开了JIRA Issue;解决方法是在开始之前重置自动启动...

@SpringBootApplication
public class So36332914Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(So36332914Application.class, args);
        JmsTemplate template = context.getBean(JmsTemplate.class);
        JmsListenerEndpointRegistry registry = context.getBean(JmsListenerEndpointRegistry.class);
        System.out.println(registry.getListenerContainerIds().size() + " containers");
        System.out.println("Running: " + registry.isRunning());

        // https://jira.spring.io/browse/SPR-14105
        for (MessageListenerContainer container : registry.getListenerContainers()) {
            ((AbstractJmsListeningContainer) container).setAutoStartup(true);
        }
        registry.start();
        System.out.println("Running: " + registry.isRunning());
        template.convertAndSend("foo", "bar");
        registry.stop();
        System.out.println("Running: " + registry.isRunning());
        context.getBean(Foo.class).latch.await(10, TimeUnit.SECONDS);
        context.close();
    }

    @Bean
    public Foo foo() {
        return new Foo();
    }

    public static class Foo {

        private final CountDownLatch latch = new CountDownLatch(1);

        @JmsListener(destination="foo")
        public void foo(String foo) {
            System.out.println(foo);
            latch.countDown();
        }

    }

}