8 Kasım 2023 Çarşamba

Spring Amqp RabbitMQ Dead Letter Queue

Örnek
Şöyle yaparız
@Configuration
public class RabbitMQConfig { public static final String QUEUE_NAME = "queue-name"; public static final String DLQ_NAME = "dlq-name"; public static final String DLX_NAME = "dlx-name"; @Bean public DirectExchange directExchange() { return new DirectExchange(DIRECT_EXCHANGE); } @Bean public Queue queue() { return new Queue(QUEUE_NAME, true); // Declare the queue as durable } @Bean public Binding binding() { return BindingBuilder.bind(queue()).to(directExchange()).with(QUEUE_NAME); } // DLQ create @Bean public Queue deadLetterQueue() { return new Queue(DLQ_NAME, true); // Declare the DLQ as durable } @Bean public DirectExchange deadLetterExchange() { return new DirectExchange(DLX_NAME); } @Bean public Binding deadLetterBinding() { return BindingBuilder.bind(deadLetterQueue()) .to(deadLetterExchange()).with(DLQ_NAME); } @Bean public Binding queueToDeadLetterExchangeBinding() { return BindingBuilder.bind(queue()) .to(deadLetterExchange()).with(QUEUE_NAME); } }
Şöyle yaparız. Burada DLQ'ya kodla gönderiliyor.
@RabbitListener(queues = "queue-name")
public void handleMessage(String message) {
  try {
    // Process the incoming message
    if (someCondition) {
      throw new Exception("Simulated exception");
    }
    // Message processing succeeded
  } catch (Exception e) {
    // Handle the exception or log it
    System.err.println("Error processing message: " + e.getMessage());
            
    // Send the message to the DLQ
    rabbitTemplate.send("direct.exchange", "dlq-name", new Message(message.getBytes()));
  }
}


Hiç yorum yok:

Yorum Gönder