使用SpringAOP拦截发送和接收消息

时间:2020-08-26 09:07:43

标签: spring-amqp spring-rabbitmq

由于某些原因,我不得不拦截发送和接收消息。 (包装邮件,并在收到邮件时对其进行解析)。

我知道MessagePostProcessor是一种拦截器,但是它将影响当前代码。因此,我正在考虑使用Spring AOP。

要发送消息,我只需拦截RabbitTemplate的sendconvertAndSend方法,就像下面的代码一样:

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

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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;
    };
}