spring boot rabbitMQ DLE不接受任何消息

时间:2017-03-08 12:27:03

标签: spring rabbitmq spring-integration spring-rabbit spring-rabbitmq

我正在开发spring-boot rabbitMQ。我正在创建一个死信队列,我可以在RabbitMQ管理员中看到“D,DLE”,但没有DLK可能是我缺少设置“x-dead-letter-routing-key”,事情是我不想要路由密钥。我的消费者中很少有人绑定到特定的交换机,如果消费者对该交换存在任何问题,那么我每次交换都会创建DLE,然后DLE连接到接收该消息并执行用户相关逻辑的交换。但是不幸的是,这不起作用,DLE没有收到任何消息。

请找到以下代码,

package com.sample.rabbit;

import org.slf4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Argument;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import    org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.ConditionalRejectingErrorHandler;
import org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ErrorHandler;

@SpringBootApplication
public class SampleRabbitApplication {

public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context = SpringApplication.run(SampleRabbitApplication.class, args);
    context.getBean(SampleRabbitApplication.class).runDemo();
    context.close();
}

@Autowired
private RabbitTemplate template;

private void runDemo() throws Exception {
    this.template.convertAndSend("sample-queue", new Foo("bar"),m -> {
        m.getMessageProperties().setHeader("__TypeId__","foo");
        return m;
    });

    this.template.convertAndSend("sample-queue", new Foo("throw"),m -> {
        m.getMessageProperties().setHeader("__TypeId__","foo");
        return m;
    });
    this.template.convertAndSend("sample-queue", new Foo("bar"), m -> {
        return new Message("some bad json".getBytes(), m.getMessageProperties());
    });
    Thread.sleep(5000);
}

@RabbitListener(
        id = "sample-queue",
        bindings = @QueueBinding(
                value = @org.springframework.amqp.rabbit.annotation.Queue(value = "sample-queue", durable = "true"),
                exchange = @org.springframework.amqp.rabbit.annotation.Exchange(value = "sample.exchange", durable = "true")
        )
)
public void handle(Foo in) {
    System.out.println("Received: " + in);
if("throw".equalsIgnoreCase(in.getFoo())){
        throw new BadRequestException("Foo contains throw so it throwed the exception.");
    }
}

@RabbitListener(
        id = "sample-dead-letter-queue",
        bindings = @QueueBinding(
                value = @org.springframework.amqp.rabbit.annotation.Queue(value = "sample-dead-letter-queue", durable = "true", arguments = {@Argument(name = "x-dead-letter-exchange",value = "sample.exchange"),@Argument(name = "x-dead-letter-routing-key",value = "#")}),
                exchange = @org.springframework.amqp.rabbit.annotation.Exchange(value = "critical.exchange", durable = "true",type = "topic")
        )
)
public void handleDLE(Message in) {
    System.out.println("Received in DLE: " + in.getBody());
}

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setMessageConverter(jsonConverter());
    factory.setErrorHandler(errorHandler());
    return factory;
}

@Bean
public ErrorHandler errorHandler() {
    return new ConditionalRejectingErrorHandler(new MyFatalExceptionStrategy());
}

@Bean
public MessageConverter jsonConverter() {
    Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
    DefaultClassMapper mapper = new DefaultClassMapper();
    mapper.setDefaultType(Foo.class);
    converter.setClassMapper(mapper);
    return new Jackson2JsonMessageConverter();
}

public static class MyFatalExceptionStrategy extends ConditionalRejectingErrorHandler.DefaultExceptionStrategy {

    private final Logger LOG = org.slf4j.LoggerFactory.getLogger(getClass());

    public boolean isFatal(Throwable t) {
        if (t instanceof ListenerExecutionFailedException && isCauseFatal(t.getCause())) {
            //To do : Here we have to configure DLE(Critical queue) and put all the messages in the critical queue.
            ListenerExecutionFailedException lefe = (ListenerExecutionFailedException) t;
            if(lefe.getFailedMessage() != null) {
                LOG.info("Failed to process inbound message from queue "
                        + lefe.getFailedMessage().getMessageProperties().getConsumerQueue()
                        + "; failed message: " + lefe.getFailedMessage(), t);
            } else {
                LOG.info("Failed to process inbound message from queue "
                        + lefe.getMessage(), t);
            }
        }
        return super.isFatal(t);
    }

    private boolean isCauseFatal(Throwable cause) {
        return cause instanceof MessageConversionException
                || cause instanceof org.springframework.messaging.converter.MessageConversionException
                || cause instanceof MethodArgumentNotValidException
                || cause instanceof MethodArgumentTypeMismatchException
                || cause instanceof NoSuchMethodException
                || cause instanceof ClassCastException
                || isUserCauseFatal(cause);
    }

    /**
     * Subclasses can override this to add custom exceptions.
     * @param cause the cause
     * @return true if the cause is fatal.
     */
    protected boolean isUserCauseFatal(Throwable cause) {
        return true;
    }


}

public static class Foo {

    private String foo;

    public Foo() {
        super();
    }

    public Foo(String foo) {
        this.foo = foo;
    }

    public String getFoo() {
        return this.foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    @Override
    public String toString() {
        return "Foo [foo=" + this.foo + "]";
    }

}
} 

My Exchanges和Queue是Direct,我的每个消费者都会使用不同的路由密钥,但它属于同一个交换,那么如何编写一个有效消耗所有失败消息的DLE。在上面的代码示例中,一条消息是成功的和其他一次失败但我在DLE中看不到失败的消息。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果使用死信交换(DLX)配置队列但没有死信路由密钥,则会使用原始路由密钥将消息路由到DLX。

处理用例的最简单方法是使DLX成为主题交换,并使用路由密钥#(所有消息的通配符)将队列绑定到该队列,并且所有错误都将转到该队列。

如果要将错误隔离到单个队列中,请将每个队列的DLQ与原始路由密钥绑定。

修改

这是正确的配置:

@RabbitListener(id = "sample-queue",
        bindings = @QueueBinding(value = @Queue(value = "sample-queue", durable = "true", arguments =
                        @Argument(name = "x-dead-letter-exchange", value = "critical.exchange")),
                    exchange = @Exchange(value = "sample.exchange", durable = "true")))
public void handle(Foo in) {
    System.out.println("Received: " + in);
}

@RabbitListener(id = "sample-dead-letter-queue", containerFactory = "noJsonContainerFactory",
        bindings = @QueueBinding(value = @Queue(value = "sample-dead-letter-queue", durable = "true"),
            exchange = @Exchange(value = "critical.exchange", durable = "true", type = "topic"),
            key = "#"))
public void handleDLE(Message in) {
    System.out.println("Received in DLE: " + new String(in.getBody()));
}

@Bean
public SimpleRabbitListenerContainerFactory noJsonContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setErrorHandler(errorHandler());
    return factory;
}