RocketMQTemplate切面失效

人中泰迪 发布于 09/29 00:15
阅读 109
收藏 0

1.场景

实现调用链路传递,使用aop拦截rocketmqtemplate的sendMessageInTransaction并注入traceId

2.环境

<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-spring-boot-starter</artifactId>
    <version>2.0.3</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.1.7.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>Greenwich.SR2</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

3.代码

@EnableWebAppAutoConfig
@SpringBootApplication
@EnableCircuitBreaker
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableFeignClients(basePackages = "com.taco.springcloud")
@MapperScan(basePackages = "com.taco.springcloud.**.dao")
public class TacoOrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(TacoOrderApplication.class, args);
    }

}
@Slf4j
@Aspect
@Component
public class RocketMQTraceAspect {

    @Pointcut("execution(* org.apache.rocketmq.spring.core.RocketMQTemplate.sendMessageInTransaction(..))")
    public void sendInTransaction() {
    }

    @Pointcut("execution(public * org.apache.rocketmq.client.producer.DefaultMQProducer.send(" +
            "org.apache.rocketmq.common.message.Message,..))")
    public void sendMessage() {
    }

    @Before(value = "sendInTransaction() || sendMessage()")
    public void onSendMessage(JoinPoint joinPoint) {
        //TODO: 拦截sendInTransaction有问题,待解决,目前通过定义RocketMQTemplate子类,修改子类方法实现
        Object[] args = joinPoint.getArgs();

        if(ArrayUtils.isEmpty(args)) {
            return;
        }

        for (Object arg : args) {
            if(arg instanceof Message) {
                setTraceId2MQ((Message) arg);
            }

            if(arg instanceof Collection) {
                Collection collection = (Collection) arg;
                for (Object o : collection) {
                    if(o instanceof Message) {
                        setTraceId2MQ((Message) o);
                        continue;
                    }
                    break;
                }
            }
        }

    }

    private void setTraceId2MQ(Message msg) {
        msg.putUserProperty(CommonConstants.TRACE_ROUTE_HEADER, MDC.get(CommonConstants.LOG_TRACE_ROUTE_NAME));
    }
加载中
0
妹子楼顶有鸽子
妹子楼顶有鸽子

为什么使用AOP,而不是代理RocketMQTemplate,或者从RocketMQ配置,Client端下手?

人中泰迪
人中泰迪
AOP底层就是代理,目前已经实现功能,但是想知道为什么AOP为什么不生效,已解决以后遇到同样的问题
返回顶部
顶部
天津时时彩