【问题标题】:How can I ask a JMS server to resend the message when an exception occurs in a JMS listener defined with the @JmsListener annotation?当使用 @JmsListener 注释定义的 JMS 侦听器发生异常时,如何要求 JMS 服务器重新发送消息?
【发布时间】:2015-07-21 04:23:07
【问题描述】:

我一直在 Springboot 应用程序中编写 JMS 侦听器。 我用了两种方式:

1) 定义一个 bean,它是 SimpleMessageListenerContainer,如下所示:

    @Bean
    SimpleMessageListenerContainer getMyMessageListenerContainer(ConnectionFactory connectionFactory) {
        MessageListenerAdapter messageListener = new MessageListenerAdapter(myService);
        messageListener.setDefaultListenerMethod("myMethodListener");
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setMessageListener(messageListener);
        container.setConnectionFactory(connectionFactory);
        container.setDestinationName("aMessageQueue");
        return container;
    }   


class MyService{
    public void myMethodListener(String argument){
        // do something...
    }
}

或 2) 使用简单的 JMSListener 注解,如下所示:

class MyService{
    @JmsListener(destination="aMessageQueue")
    public void myMethodListener(String argument) {
        // do something...
    }
}

我喜欢最后一种方法。它非常简单,并且非常简单地记录了代码。不幸的是,我注意到这两种方式的行为完全不同。

如果方法1)中抛出异常,JMS服务器会重新发送消息给监听器。在方法 2) 中,如果抛出异常,服务器不会重试向侦听器发送消息。

当使用 JMSListener 注解定义的监听器发生异常时,如何告诉服务器重新发送消息?

感谢您的帮助。

【问题讨论】:

  • 它们是不同的,第一个使用 SimpleMessageListenerContainer 而第二个使用 DefaultMessageListenerContainer 行为不同。如果你有一个事务管理器(例如对于 JPA)DefaultMessageListenerContainer 应该有事务行为和错误回滚(如果它是一个运行时异常!)如果你没有在你的配置中添加一个JmsTransactionManager。或者完全自己configureJMS 环境。
  • 感谢 mdeinum 指导进入新领域。我没有在这个项目中使用 JPA,无法访问 SQL DB。所以我尝试了很多东西。我为我找到的最简单的解决方案是加载“spring-boot-starter-jta-bitronix”,这样就成功了。
  • 如果您不需要多个事务性资源,因为这将启用 XA,而 XA 与本地事务相比具有额外的成本。如果您只需要 JMS 的事务,最简单的方法就是注册一个 JmsTransactionManager
  • 如何在 Spring Boot 应用程序中做到这一点?
  • 只需将其添加为@Bean...

标签: annotations jms listener spring-boot


【解决方案1】:

我只是在 pom.xml 中添加了以下依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jta-bitronix</artifactId>
    </dependency>

我的听众现在看起来像这样:

class MyService{
  @JmsListener(destination="aMessageQueue")
  public void myMethodListener(String argument) {
    // do something...
  }
}

即使在我的侦听器中抛出异常,它们也会再次被调用。

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2013-02-17
    相关资源
    最近更新 更多