首页 > 解决方案 > 如何处理异常 RabbitMQ 微服务

问题描述

我使用spring boot rabbitMQ Sender。方法返回Integer

try {
    return rabbitTemplate.convertSendAndReceive(exchange, routingKey,
        mapper.writeValueAsString(request),
        correlationData);
} catch (Exception e) {
    log.error(e.getMessage(), e);
}

在接收方,回复:

@RabbitListener(queues = "testQueue", returnExceptions = "true")
public class TestReply {

    @RabbitHandler
    public Integer handle(String message) throws JsonProcessingException {
        throw new IllegalArgumentException()
    }
}

我想IllegalArgumentException在发件人中处理。但我得到的事实是

org.springframework.amqp.support.converter.MessageConversionException: Failed to convert Message content
Cannot deserialize value of type `java.lang.Integer` from Object value (token `JsonToken.START_OBJECT`)

请帮我!

标签: javaspring-bootrabbitmqspring-rabbit

解决方案


@RabbitListener.returnExceptions().

    /**
     * Set to "true" to cause exceptions thrown by the listener to be sent to the sender
     * using normal {@code replyTo/@SendTo} semantics. When false, the exception is thrown
     * to the listener container and normal retry/DLQ processing is performed.
     * @return true to return exceptions. If the client side uses a
     * {@code RemoteInvocationAwareMessageConverterAdapter} the exception will be re-thrown.
     * Otherwise, the sender will receive a {@code RemoteInvocationResult} wrapping the
     * exception.
     * @since 2.0
     */
    String returnExceptions() default "";

但是,这仅适用于 Java 序列化(不是 JSON),因为异常通常不是 JSON 友好的。

另一种方法是添加一个errorHandler并返回一些特殊值来告诉客户端发生了异常。

https://docs.spring.io/spring-amqp/docs/current/reference/html/#annotation-error-handling


推荐阅读