如何在 Spring Boot Java 中将失败消息推送到 Azure 服务总线死信队列?

问题描述

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

我根据 Spring 文档尝试的示例代码

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

How to move error message to Azure dead letter queue using Java?

解决方法

先接收消息,然后使用

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

(锁定令牌是从消息属性中获取的。)

API reference