记录springboot集成rocketmq关于tag的坑

新项目使用springboot的若依框架集成rocketmq,选择集成RocketMQTemplate这种方式实现消息的发送和接收。

1.客户端发送代码,此处回调方法里有些业务不用关注,只关心发送方法

@Component
public class RocketMqHelper {

    Logger logger = LoggerFactory.getLogger(RocketMqHelper.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void send(ReqMsg msg){
        rocketMQTemplate.asyncSend(msg.getMsg().getTopic()+":"+msg.getMsg().getTags(),
        msg.getMsg(),
        new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.debug("msgid:{} 发送成功" , sendResult.getMsgId());
                logger.debug("发送mq成功后要执行的service:                
                          {}",msg.getMsg().getSendAfterMethod());
                IsaveSendAfterMqLog saveSendAfterMqLog = 
                SpringUtils.getBean(msg.getMsg().getSendAfterMethod());
                saveSendAfterMqLog.saveSendAfterMqLog(new 
                               SendAfterLog(msg.getMsg(),sendResult,"0"));
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("mq发送异常!{}",throwable.toString());
                logger.debug("发送mq失败后执行的service: 
                               {}",msg.getMsg().getSendAfterMethod());
                //异常描述截取500 length入库
                msg.getMsg().putUserProperty("exceptionDesc",throwable.toString());
                IsaveSendAfterMqLog saveSendAfterMqLog = 
                SpringUtils.getBean(msg.getMsg().getSendAfterMethod());
                saveSendAfterMqLog.saveSendAfterMqLog(new 
                                     SendAfterLog(msg.getMsg(),"1"));
            }
        });
    }


}

2.服务端监听消息

@Service
@RocketMQMessageListener(topic = "${rocketmq.topic}", consumerGroup = "${rocketmq.consumer.group}",
        selectorExpression="${rocketmq.tags}")
public class CbiRocketmqConsumer implements RocketMQListener {

    Logger logger = LoggerFactory.getLogger(CbiRocketmqConsumer.class);


    @Override
    public void onMessage(CbiMsg message) {
        String msgBody = new String(message.getBody());
        String serviceName = message.getTags();
        logger.info("本次消费服务名称:{}",serviceName);
        AbSaveReceiveAfter saveReceiveAfter = SpringUtils.getBean(serviceName);
        saveReceiveAfter.saveReceiveAfter(new RecevieAfterLog(message,     
        Constants.CONSUME_SUCCESS));//默认消费成功
    }
}
@RocketMQMessageListener这个注解里selectorExpression默认是*,接收topic下全部消息。想动态对tags进行配置。于是利用springboot获取yml配置。写死的时候没有问题,但是改成$表达式配置后怎么都收不到消息,经排查居然是selectorExpression这个不支持配置,会原封的按表达式进入MQ容器初始化。然而注解里面的topic,comsumerGroup都可以正常拿到配置值。

翻源码发现问题所在,项目启动时,在ListenerContainerConfiguration在这个类里初始化mq容器时,对配置进行赋值

 private DefaultRocketMQListenerContainer createRocketMQListenerContainer(Object bean, RocketMQMessageListener annotation) {
        DefaultRocketMQListenerContainer container = new 
                                    DefaultRocketMQListenerContainer();

        container.setNameServer(rocketMQProperties.getNameServer());
        container.setTopic(environment.resolvePlaceholders(annotation.topic()));
        container.setConsumerGroup(environment.resolvePlaceholders
                                                  (annotation.consumerGroup()));
        container.setRocketMQMessageListener(annotation);
        container.setRocketMQListener((RocketMQListener) bean);
        container.setObjectMapper(objectMapper);

        return container;
    }

 

topic和comsumerGroup都在springboot环境里获取配置值了,唯独selectorExpression这个没有,直接默认注解里的。下面的问题就是需要自己在项目启动,springboot容器起来,但是rocketmq容器未起的时候,动态去改注解里配置的值。然后让Rocketmq启动。

**
 *  因为RocketMQMessageListener不提供动态配置功能
 *  springboot初始化后rocket容器初始化前利用反射动态改变
 *  RocketMQMessageListener注解selectorExpression的值
 *
 *
 */
@Component
public class ChangeSelectorExpressionBeforeMqStart implements InitializingBean {

    @Value("${rocketmq.consumer.tags}")
    private String tags;

    @Override
    public void afterPropertiesSet() throws Exception {
        RocketMQMessageListener annoTable = 
         CbiRocketmqConsumer.class.getAnnotation(RocketMQMessageListener.class);
        // 获取代理处理器
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(annoTable);
        // 获取私有 memberValues 属性
        Field f = invocationHandler.getClass().getDeclaredField("memberValues");
        f.setAccessible(true);
        // 获取实例的属性map
        Map memberValues = (Map) 
        f.get(invocationHandler);
        // 修改属性值
        memberValues.put("selectorExpression", tags);

    }

}

问题解决。。

你可能感兴趣的:(rocketmq)