首页 > 解决方案 > 使用SpringAOP拦截发送和接收消息

问题描述

由于某些原因,我必须拦截发送和接收消息。(包装消息并在收到消息时解析消息)。

我知道MessagePostProcessor是拦截器的一种形式,但它会影响当前代码。所以,我正在考虑使用 Spring AOP。

对于发送消息,我可以简单的拦截 RabbitTemplate 的sendconvertAndSend方法,如下代码:</p>

@Around("execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.send(..))")

但是对于接收消息,哪种方法最好拦截呢?在大多数情况下,RabbitListener用于接收消息。

任何帮助表示赞赏。

标签: spring-amqpspring-rabbit

解决方案


将一个添加Advice到侦听器容器的adviceChain. 请参阅https://docs.spring.io/spring-amqp/docs/2.2.10.RELEASE/reference/html/#containerAttributes

编辑

@Bean
public MethodInterceptor advice() {
    return invocation -> {
        Message message = (Message) invocation.getArguments()[0];
        try {
            // before
            invocation.proceed();
            // after
        }
        catch (Exception e) {
            // ...
            throw e;
        }
        finally {
            // ...
        }
        return null;
    };
}

推荐阅读