首页 > 解决方案 > 如何在 Spring Boot Java 中将失败消息推送到 Azure 服务总线死信队列?

问题描述

我正在使用 JMS 侦听器从 Azure 主题读取消息并处理消息,一旦该过程完成,我将推回另一个主题。我在 spring 文档的帮助下成功完成了功能。现在我需要处理失败消息 - 错误处理程序。如果我们在读取或处理消息时出现异常,则意味着我需要将其推送到死信队列。

我尝试基于 Spring Documentation 的示例代码。

@Component
public class Receiver {

  @JmsListener(destination = "mailbox", containerFactory = "myFactory")
  public void receiveMessage(Email email) {
    System.out.println("Received <" + email + ">");
  }

}

@SpringBootApplication
@EnableJms
public class Application {

  @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.
    return factory;
  }

  @Bean // Serialize message content to json using TextMessage
  public MessageConverter jacksonJmsMessageConverter() {
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setTargetType(MessageType.TEXT);
    converter.setTypeIdPropertyName("_type");
    return converter;
  }

  public static void main(String[] args) {
    // Launch the application
    ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

    JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);

    // Send a message with a POJO - the template reuse the message converter
    System.out.println("Sending an email message.");
    jmsTemplate.convertAndSend("mailbox", new Email("info@example.com", "Hello"));
  }

}

任何人,请就此向我提出建议

参考 https://spring.io/guides/gs/messaging-jms/

如何使用 Java 将错误消息移动到 Azure 死信队列?

标签: azureservicebusspring-jmsazure-servicebus-topicsdead-letter

解决方案


首先,接收消息,然后使用

com.microsoft.azure.servicebus -> QueueClient -> deadLetter(UUID lockToken)

(locktoken 是从消息属性中获取的。)

API 参考


推荐阅读