@JmsListener usage for publish-subscribe topic

后端 未结 2 1798
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 19:11

I am trying to create example for publish-subscribe based on @JmsListener annotation: https://github.com/lkrnac/book-eiws-code-samples/tree/master/05-jms/0515-publish-subscr

相关标签:
2条回答
  • 2020-12-28 19:34

    Switching the default destination type of a @JmsListener from Queue to Topic can be done completely in Java without modifying the properties or using XML.

    The Spring guide contains an example for customizing the default settings provided by DefaultMessageListenerContainer.

    It requires defining a custom bean like follows:

    @Bean
    public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                                                    DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        // This provides all boot's default to this factory, including the message converter
        configurer.configure(factory, connectionFactory);
        // You could still override some of Boot's default if necessary.
        factory.setPubSubDomain(true);
        return factory;
    }
    

    This can then be used in the @JmsListener annotated method:

    @JmsListener(destination = "mailbox", containerFactory = "myFactory")
    public void receiveMessage(Email email) {
        // implementation
    }
    
    0 讨论(0)
  • 2020-12-28 19:48

    When using a @JmsListener it uses a DefaultMessageListenerContainer which extends JmsDestinationAccessor which by default has the pubSubDomain set to false. When this property is false it is operating on a queue. If you want to use topics you have to set this properties value to true.

    As you are using Spring Boot you can quite easily set this property to true by adding the spring.jms.pub-sub-domain property to the application.properties and set it to true.

    spring.jms.pub-sub-domain=true
    

    When using a @JmsListener it is looking for a jmsListenerContainerFactory named bean, if that isn't available a default one is expected. You can also include your own bean and programmatically set this property yo true.

    @Bean
    public DefaultMessageListenerContainer jmsListenerContainerFactory() {
        DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
        dmlc.setPubSubDomain(true);
        // Other configuration here
        return dmlc;
    }
    

    This would of course also work but would be more work, more information on this can be found in the documentation of the @EnableJms annotation.

    0 讨论(0)
提交回复
热议问题