经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » RocketMQ » 查看文章
SpringBoot整合RocketMQ,老鸟们都是这么玩的!
来源:cnblogs  作者:JAVA日知录  时间:2023/4/10 9:01:45  对本文有异议

今天我们来讨论如何在项目开发中优雅地使用RocketMQ。本文分为三部分,第一部分实现SpringBoot与RocketMQ的整合,第二部分解决在使用RocketMQ过程中可能遇到的一些问题并解决他们,第三部分介绍如何封装RocketMQ以便更好地使用。

1. SpringBoot整合RocketMQ

在SpringBoot中集成RocketMQ,只需要简单四步:

  1. 引入相关依赖
  1. <dependency>
  2. <groupId>org.apache.rocketmq</groupId>
  3. <artifactId>rocketmq-spring-boot-starter</artifactId>
  4. </dependency>
  1. 添加RocketMQ的相关配置
  1. rocketmq:
  2. consumer:
  3. group: springboot_consumer_group
  4. # 一次拉取消息最大值,注意是拉取消息的最大值而非消费最大值
  5. pull-batch-size: 10
  6. name-server: 10.5.103.6:9876
  7. producer:
  8. # 发送同一类消息的设置为同一个group,保证唯一
  9. group: springboot_producer_group
  10. # 发送消息超时时间,默认3000
  11. sendMessageTimeout: 10000
  12. # 发送消息失败重试次数,默认2
  13. retryTimesWhenSendFailed: 2
  14. # 异步消息重试此处,默认2
  15. retryTimesWhenSendAsyncFailed: 2
  16. # 消息最大长度,默认1024 * 1024 * 4(默认4M)
  17. maxMessageSize: 4096
  18. # 压缩消息阈值,默认4k(1024 * 4)
  19. compressMessageBodyThreshold: 4096
  20. # 是否在内部发送失败时重试另一个broker,默认false
  21. retryNextServer: false
  1. 使用提供的模板工具类RocketMQTemplate发送消息
  1. @RestController
  2. public class NormalProduceController {
  3. @Setter(onMethod_ = @Autowired)
  4. private RocketMQTemplate rocketmqTemplate;
  5. @GetMapping("/test")
  6. public SendResult test() {
  7. Message<String> msg = MessageBuilder.withPayload("Hello,RocketMQ").build();
  8. SendResult sendResult = rocketmqTemplate.send(topic, msg);
  9. }
  10. }
  1. 实现RocketMQListener接口消费消息
  1. import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
  2. import org.apache.rocketmq.spring.core.RocketMQListener;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. @RocketMQMessageListener(topic = "your_topic_name", consumerGroup = "your_consumer_group_name")
  6. public class MyConsumer implements RocketMQListener<String> {
  7. @Override
  8. public void onMessage(String message) {
  9. // 处理消息的逻辑
  10. System.out.println("Received message: " + message);
  11. }
  12. }

以上4步即可实现SpringBoot与RocketMQ的整合,这部分属于基础知识,不做过多说明。

2 使用RocketMQ会遇到的问题

以下是一些在SpringBoot中使用RocketMQ时常遇到的问题,现在为您逐一解决。

2.1 WARN No appenders could be found for logger

启动项目时会在日志中看到如下告警

  1. RocketMQLog:WARN No appenders could be found for logger (io.netty.util.internal.InternalThreadLocalMap).
  2. RocketMQLog:WARN Please initialize the logger system properly.

此时我们只需要在启动类中设置环境变量 rocketmq.client.logUseSlf4j 为 true 明确指定RocketMQ的日志框架

  1. @SpringBootApplication
  2. public class RocketDemoApplication {
  3. public static void main(String[] args) {
  4. /*
  5. * 指定使用的日志框架,否则将会告警
  6. * RocketMQLog:WARN No appenders could be found for logger (io.netty.util.internal.InternalThreadLocalMap).
  7. * RocketMQLog:WARN Please initialize the logger system properly.
  8. */
  9. System.setProperty("rocketmq.client.logUseSlf4j", "true");
  10. SpringApplication.run(RocketDemoApplication.class, args);
  11. }
  12. }

同时还得在配置文件中调整日志级别,不然在控制台会一直看到broker的日志信息

  1. logging:
  2. level:
  3. RocketmqClient: ERROR
  4. io:
  5. netty: ERROR

2.2 不支持LocalDate 和 LocalDateTime

在使用Java8后经常会使用LocalDate/LocalDateTime这两个时间类型字段,然而RocketMQ原始配置并不支持Java时间类型,当我们发送的实体消息中包含上述两个字段时,消费端在消费时会出现如下所示的错误。

比如生产者的代码如下:

  1. @GetMapping("/test")
  2. public void test(){
  3. //普通消息无返回值,只负责发送消息?不等待服务器回应且没有回调函数触发。
  4. RocketMessage rocketMessage = RocketMessage.builder().
  5. id(1111L).
  6. message("hello,world")
  7. .localDate(LocalDate.now())
  8. .localDateTime(LocalDateTime.now())
  9. .build();
  10. rocketmqTemplate.convertAndSend(destination,rocketMessage);
  11. }

消费者的代码如下:

  1. @Component
  2. @RocketMQMessageListener(consumerGroup = "springboot_consumer_group",topic = "consumer_topic")
  3. public class RocketMQConsumer implements RocketMQListener<RocketMessage> {
  4. @Override
  5. public void onMessage(RocketMessage message) {
  6. System.out.println("消费消息-" + message);
  7. }
  8. }

消费者开始消费时会出现类型转换异常错误Cannot construct instance of java.time.LocalDate,错误详情如下:

image-20230322163904100

原因:RocketMQ内置使用的转换器是RocketMQMessageConverter,转换Json时使用的是MappingJackson2MessageConverter,但是这个转换器不支持时间类型。

解决办法:需要自定义消息转换器,将MappingJackson2MessageConverter进行替换,并添加支持时间模块

  1. @Configuration
  2. public class RocketMQEnhanceConfig {
  3. /**
  4. * 解决RocketMQ Jackson不支持Java时间类型配置
  5. * 源码参考:{@link org.apache.rocketmq.spring.autoconfigure.MessageConverterConfiguration}
  6. */
  7. @Bean
  8. @Primary
  9. public RocketMQMessageConverter enhanceRocketMQMessageConverter(){
  10. RocketMQMessageConverter converter = new RocketMQMessageConverter();
  11. CompositeMessageConverter compositeMessageConverter = (CompositeMessageConverter) converter.getMessageConverter();
  12. List<MessageConverter> messageConverterList = compositeMessageConverter.getConverters();
  13. for (MessageConverter messageConverter : messageConverterList) {
  14. if(messageConverter instanceof MappingJackson2MessageConverter){
  15. MappingJackson2MessageConverter jackson2MessageConverter = (MappingJackson2MessageConverter) messageConverter;
  16. ObjectMapper objectMapper = jackson2MessageConverter.getObjectMapper();
  17. objectMapper.registerModules(new JavaTimeModule());
  18. }
  19. }
  20. return converter;
  21. }
  22. }

2.3 RockeMQ环境隔离

在使用RocketMQ时,通常会在代码中直接指定消息主题(topic),而且开发环境和测试环境可能共用一个RocketMQ环境。如果没有进行处理,在开发环境发送的消息就可能被测试环境的消费者消费,测试环境发送的消息也可能被开发环境的消费者消费,从而导致数据混乱的问题。

为了解决这个问题,我们可以根据不同的环境实现自动隔离。通过简单配置一个选项,如dev、test、prod等不同环境,所有的消息都会被自动隔离。例如,当发送的消息主题为consumer_topic时,可以自动在topic后面加上环境后缀,如consumer_topic_dev

那么,我们该如何实现呢?

可以编写一个配置类实现BeanPostProcessor,并重写postProcessBeforeInitialization方法,在监听器实例初始化前修改对应的topic。

BeanPostProcessor是Spring框架中的一个接口,它的作用是在Spring容器实例化、配置完bean之后,在bean初始化前后进行一些额外的处理工作。

具体来说,BeanPostProcessor接口定义了两个方法:

  • postProcessBeforeInitialization(Object bean, String beanName): 在bean初始化之前进行处理,可以对bean做一些修改等操作。
  • postProcessAfterInitialization(Object bean, String beanName): 在bean初始化之后进行处理,可以进行一些清理或者其他操作。

BeanPostProcessor可以在应用程序中对Bean的创建和初始化过程进行拦截和修改,对Bean的生命周期进行干预和操作。它可以对所有的Bean类实例进行增强处理,使得开发人员可以在Bean初始化前后自定义一些操作,从而实现自己的业务需求。比如,可以通过BeanPostProcessor来实现注入某些必要的属性值、加入某一个对象等等。

实现方案如下:

  1. 在配置文件中增加相关配置
  1. rocketmq:
  2. enhance:
  3. # 启动隔离,用于激活配置类EnvironmentIsolationConfig
  4. # 启动后会自动在topic上拼接激活的配置文件,达到自动隔离的效果
  5. enabledIsolation: true
  6. # 隔离环境名称,拼接到topic后,topic_dev,默认空字符串
  7. environment: dev
  1. 新增配置类,在实例化消息监听者之前把topic修改掉
  1. @Configuration
  2. public class EnvironmentIsolationConfig implements BeanPostProcessor {
  3. @Value("${rocketmq.enhance.enabledIsolation:true}")
  4. private boolean enabledIsolation;
  5. @Value("${rocketmq.enhance.environment:''}")
  6. private String environmentName;
  7. /**
  8. * 在装载Bean之前实现参数修改
  9. */
  10. @Override
  11. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  12. if(bean instanceof DefaultRocketMQListenerContainer){
  13. DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;
  14. //拼接Topic
  15. if(enabledIsolation && StringUtils.hasText(environmentName)){
  16. container.setTopic(String.join("_", container.getTopic(),environmentName));
  17. }
  18. return container;
  19. }
  20. return bean;
  21. }
  22. }
  1. 启动项目可以看到日志中消息监听的队列已经被修改了
  1. 2023-03-23 17:04:59.726 [main] INFO o.a.r.s.support.DefaultRocketMQListenerContainer:290 - running container: DefaultRocketMQListenerContainer{consumerGroup='springboot_consumer_group', nameServer='10.5.103.6:9876', topic='consumer_topic_dev', consumeMode=CONCURRENTLY, selectorType=TAG, selectorExpression='*', messageModel=CLUSTERING}

3. RocketMQ二次封装

在解释为什么要二次封装之前先来看看RocketMQ官方文档中推荐的最佳实践

  1. 消息发送成功或者失败要打印消息日志,用于业务排查问题。

  2. 如果消息量较少,建议在消费入口方法打印消息,消费耗时等,方便后续排查问题。

  3. RocketMQ 无法避免消息重复(Exactly-Once),所以如果业务对消费重复非常敏感,务必要在业务层面进行去重处理。可以借助关系数据库进行去重。首先需要确定消息的唯一键,可以是msgId,也可以是消息内容中的唯一标识字段,例如订单Id等。

上面三个步骤基本每次发送消息或者消费消息都要实现,属于重复动作。

接下来讨论的是在RocketMQ中发送消息时选择何种消息类型最为合适。

在RocketMQ中有四种可选格式:

  1. 发送Json对象
  2. 发送转Json后的String对象
  3. 根据业务封装对应实体类
  4. 直接使用原生MessageExt接收。

对于如何选择消息类型,需要考虑到消费者在不查看消息发送者的情况下,如何获取消息的含义。因此,在这种情况下,使用第三种方式即根据业务封装对应实体类的方式最为合适,也是大多数开发者在发送消息时的常用方式。

有了上面两点结论以后我们来看看为什么要对RocketMQ二次封装。

3.1 为什么要二次封装

按照上述最佳实践,一个完整的消息传递链路从生产到消费应包括 准备消息、发送消息、记录消息日志、处理发送失败、记录接收消息日志、处理业务逻辑、异常处理和异常重试 等步骤。

虽然使用原生RocketMQ可以完成这些动作,但每个生产者和消费者都需要编写大量重复的代码来完成相同的任务,这就是需要进行二次封装的原因。我们希望通过二次封装,**生产者只需准备好消息实体并调用封装后的工具类发送,而消费者只需处理核心业务逻辑,其他公共逻辑会得到统一处理。 **

在二次封装中,关键是找出框架在日常使用中所涵盖的许多操作,以及区分哪些操作是可变的,哪些是不变的。以上述例子为例,实际上只有生产者的消息准备和消费者的业务处理是可变的操作,需要根据需求进行处理,而其他步骤可以固定下来形成一个模板。

当然,本文提到的二次封装不是指对源代码进行封装,而是针对工具的原始使用方式进行的封装。可以将其与Mybatis和Mybatis-plus区分开来。这两者都能完成任务,只不过Mybatis-plus更为简单便捷。

3.2 实现二次封装

实现二次封装需要创建一个自定义的starter,这样其他项目只需要依赖此starter即可使用封装功能。同时,在自定义starter中还需要解决文章第二部分中提到的一些问题。

代码结构如下所示:

image-20230403160031944

3.2.1 消息实体类的封装

  1. /**
  2. * 消息实体,所有消息都需要继承此类
  3. * 公众号:JAVA日知录
  4. */
  5. @Data
  6. public abstract class BaseMessage {
  7. /**
  8. * 业务键,用于RocketMQ控制台查看消费情况
  9. */
  10. protected String key;
  11. /**
  12. * 发送消息来源,用于排查问题
  13. */
  14. protected String source = "";
  15. /**
  16. * 发送时间
  17. */
  18. protected LocalDateTime sendTime = LocalDateTime.now();
  19. /**
  20. * 重试次数,用于判断重试次数,超过重试次数发送异常警告
  21. */
  22. protected Integer retryTimes = 0;
  23. }

后面所有发送的消息实体都需要继承此实体类。

3.2.2 消息发送工具类的封装

  1. @Slf4j
  2. @RequiredArgsConstructor(onConstructor = @__(@Autowired))
  3. public class RocketMQEnhanceTemplate {
  4. private final RocketMQTemplate template;
  5. @Resource
  6. private RocketEnhanceProperties rocketEnhanceProperties;
  7. public RocketMQTemplate getTemplate() {
  8. return template;
  9. }
  10. /**
  11. * 根据系统上下文自动构建隔离后的topic
  12. * 构建目的地
  13. */
  14. public String buildDestination(String topic, String tag) {
  15. topic = reBuildTopic(topic);
  16. return topic + ":" + tag;
  17. }
  18. /**
  19. * 根据环境重新隔离topic
  20. * @param topic 原始topic
  21. */
  22. private String reBuildTopic(String topic) {
  23. if(rocketEnhanceProperties.isEnabledIsolation() && StringUtils.hasText(rocketEnhanceProperties.getEnvironment())){
  24. return topic +"_" + rocketEnhanceProperties.getEnvironment();
  25. }
  26. return topic;
  27. }
  28. /**
  29. * 发送同步消息
  30. */
  31. public <T extends BaseMessage> SendResult send(String topic, String tag, T message) {
  32. // 注意分隔符
  33. return send(buildDestination(topic,tag), message);
  34. }
  35. public <T extends BaseMessage> SendResult send(String destination, T message) {
  36. // 设置业务键,此处根据公共的参数进行处理
  37. // 更多的其它基础业务处理...
  38. Message<T> sendMessage = MessageBuilder.withPayload(message).setHeader(RocketMQHeaders.KEYS, message.getKey()).build();
  39. SendResult sendResult = template.syncSend(destination, sendMessage);
  40. // 此处为了方便查看给日志转了json,根据选择选择日志记录方式,例如ELK采集
  41. log.info("[{}]同步消息[{}]发送结果[{}]", destination, JSONObject.toJSON(message), JSONObject.toJSON(sendResult));
  42. return sendResult;
  43. }
  44. /**
  45. * 发送延迟消息
  46. */
  47. public <T extends BaseMessage> SendResult send(String topic, String tag, T message, int delayLevel) {
  48. return send(buildDestination(topic,tag), message, delayLevel);
  49. }
  50. public <T extends BaseMessage> SendResult send(String destination, T message, int delayLevel) {
  51. Message<T> sendMessage = MessageBuilder.withPayload(message).setHeader(RocketMQHeaders.KEYS, message.getKey()).build();
  52. SendResult sendResult = template.syncSend(destination, sendMessage, 3000, delayLevel);
  53. log.info("[{}]延迟等级[{}]消息[{}]发送结果[{}]", destination, delayLevel, JSONObject.toJSON(message), JSONObject.toJSON(sendResult));
  54. return sendResult;
  55. }
  56. }

这里封装了一个消息发送类,实现了日志记录以及自动重建topic的功能(即生产者实现环境隔离),后面项目中只需要注入RocketMQEnhanceTemplate来实现消息的发送。

3.2.3 消费者的封装

  1. @Slf4j
  2. public abstract class EnhanceMessageHandler<T extends BaseMessage> {
  3. /**
  4. * 默认重试次数
  5. */
  6. private static final int MAX_RETRY_TIMES = 3;
  7. /**
  8. * 延时等级
  9. */
  10. private static final int DELAY_LEVEL = EnhanceMessageConstant.FIVE_SECOND;
  11. @Resource
  12. private RocketMQEnhanceTemplate rocketMQEnhanceTemplate;
  13. /**
  14. * 消息处理
  15. *
  16. * @param message 待处理消息
  17. * @throws Exception 消费异常
  18. */
  19. protected abstract void handleMessage(T message) throws Exception;
  20. /**
  21. * 超过重试次数消息,需要启用isRetry
  22. *
  23. * @param message 待处理消息
  24. */
  25. protected abstract void handleMaxRetriesExceeded(T message);
  26. /**
  27. * 是否需要根据业务规则过滤消息,去重逻辑可以在此处处理
  28. * @param message 待处理消息
  29. * @return true: 本次消息被过滤,false:不过滤
  30. */
  31. protected boolean filter(T message) {
  32. return false;
  33. }
  34. /**
  35. * 是否异常时重复发送
  36. *
  37. * @return true: 消息重试,false:不重试
  38. */
  39. protected abstract boolean isRetry();
  40. /**
  41. * 消费异常时是否抛出异常
  42. * 返回true,则由rocketmq机制自动重试
  43. * false:消费异常(如果没有开启重试则消息会被自动ack)
  44. */
  45. protected abstract boolean throwException();
  46. /**
  47. * 最大重试次数
  48. *
  49. * @return 最大重试次数,默认5次
  50. */
  51. protected int getMaxRetryTimes() {
  52. return MAX_RETRY_TIMES;
  53. }
  54. /**
  55. * isRetry开启时,重新入队延迟时间
  56. * @return -1:立即入队重试
  57. */
  58. protected int getDelayLevel() {
  59. return DELAY_LEVEL;
  60. }
  61. /**
  62. * 使用模板模式构建消息消费框架,可自由扩展或删减
  63. */
  64. public void dispatchMessage(T message) {
  65. // 基础日志记录被父类处理了
  66. log.info("消费者收到消息[{}]", JSONObject.toJSON(message));
  67. if (filter(message)) {
  68. log.info("消息id{}不满足消费条件,已过滤。",message.getKey());
  69. return;
  70. }
  71. // 超过最大重试次数时调用子类方法处理
  72. if (message.getRetryTimes() > getMaxRetryTimes()) {
  73. handleMaxRetriesExceeded(message);
  74. return;
  75. }
  76. try {
  77. long now = System.currentTimeMillis();
  78. handleMessage(message);
  79. long costTime = System.currentTimeMillis() - now;
  80. log.info("消息{}消费成功,耗时[{}ms]", message.getKey(),costTime);
  81. } catch (Exception e) {
  82. log.error("消息{}消费异常", message.getKey(),e);
  83. // 是捕获异常还是抛出,由子类决定
  84. if (throwException()) {
  85. //抛出异常,由DefaultMessageListenerConcurrently类处理
  86. throw new RuntimeException(e);
  87. }
  88. //此时如果不开启重试机制,则默认ACK了
  89. if (isRetry()) {
  90. handleRetry(message);
  91. }
  92. }
  93. }
  94. protected void handleRetry(T message) {
  95. // 获取子类RocketMQMessageListener注解拿到topic和tag
  96. RocketMQMessageListener annotation = this.getClass().getAnnotation(RocketMQMessageListener.class);
  97. if (annotation == null) {
  98. return;
  99. }
  100. //重新构建消息体
  101. String messageSource = message.getSource();
  102. if(!messageSource.startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
  103. message.setSource(EnhanceMessageConstant.RETRY_PREFIX + messageSource);
  104. }
  105. message.setRetryTimes(message.getRetryTimes() + 1);
  106. SendResult sendResult;
  107. try {
  108. // 如果消息发送不成功,则再次重新发送,如果发送异常则抛出由MQ再次处理(异常时不走延迟消息)
  109. sendResult = rocketMQEnhanceTemplate.send(annotation.topic(), annotation.selectorExpression(), message, getDelayLevel());
  110. } catch (Exception ex) {
  111. // 此处捕获之后,相当于此条消息被消息完成然后重新发送新的消息
  112. //由生产者直接发送
  113. throw new RuntimeException(ex);
  114. }
  115. // 发送失败的处理就是不进行ACK,由RocketMQ重试
  116. if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
  117. throw new RuntimeException("重试消息发送失败");
  118. }
  119. }
  120. }

使用模版设计模式定义了消息消费的骨架,实现了日志打印,异常处理,异常重试等公共逻辑,消息过滤(查重)、业务处理则交由子类实现。

3.2.4 基础配置类

  1. @Configuration
  2. @EnableConfigurationProperties(RocketEnhanceProperties.class)
  3. public class RocketMQEnhanceAutoConfiguration {
  4. /**
  5. * 注入增强的RocketMQEnhanceTemplate
  6. */
  7. @Bean
  8. public RocketMQEnhanceTemplate rocketMQEnhanceTemplate(RocketMQTemplate rocketMQTemplate){
  9. return new RocketMQEnhanceTemplate(rocketMQTemplate);
  10. }
  11. /**
  12. * 解决RocketMQ Jackson不支持Java时间类型配置
  13. * 源码参考:{@link org.apache.rocketmq.spring.autoconfigure.MessageConverterConfiguration}
  14. */
  15. @Bean
  16. @Primary
  17. public RocketMQMessageConverter enhanceRocketMQMessageConverter(){
  18. RocketMQMessageConverter converter = new RocketMQMessageConverter();
  19. CompositeMessageConverter compositeMessageConverter = (CompositeMessageConverter) converter.getMessageConverter();
  20. List<MessageConverter> messageConverterList = compositeMessageConverter.getConverters();
  21. for (MessageConverter messageConverter : messageConverterList) {
  22. if(messageConverter instanceof MappingJackson2MessageConverter){
  23. MappingJackson2MessageConverter jackson2MessageConverter = (MappingJackson2MessageConverter) messageConverter;
  24. ObjectMapper objectMapper = jackson2MessageConverter.getObjectMapper();
  25. objectMapper.registerModules(new JavaTimeModule());
  26. }
  27. }
  28. return converter;
  29. }
  30. /**
  31. * 环境隔离配置
  32. */
  33. @Bean
  34. @ConditionalOnProperty(name="rocketmq.enhance.enabledIsolation", havingValue="true")
  35. public EnvironmentIsolationConfig environmentSetup(RocketEnhanceProperties rocketEnhanceProperties){
  36. return new EnvironmentIsolationConfig(rocketEnhanceProperties);
  37. }
  38. }
  1. public class EnvironmentIsolationConfig implements BeanPostProcessor {
  2. private RocketEnhanceProperties rocketEnhanceProperties;
  3. public EnvironmentIsolationConfig(RocketEnhanceProperties rocketEnhanceProperties) {
  4. this.rocketEnhanceProperties = rocketEnhanceProperties;
  5. }
  6. /**
  7. * 在装载Bean之前实现参数修改
  8. */
  9. @Override
  10. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  11. if(bean instanceof DefaultRocketMQListenerContainer){
  12. DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;
  13. if(rocketEnhanceProperties.isEnabledIsolation() && StringUtils.hasText(rocketEnhanceProperties.getEnvironment())){
  14. container.setTopic(String.join("_", container.getTopic(),rocketEnhanceProperties.getEnvironment()));
  15. }
  16. return container;
  17. }
  18. return bean;
  19. }
  20. }
  1. @ConfigurationProperties(prefix = "rocketmq.enhance")
  2. @Data
  3. public class RocketEnhanceProperties {
  4. private boolean enabledIsolation;
  5. private String environment;
  6. }

3.3 封装后的使用

3.3.1 引入依赖

  1. <dependency>
  2. <groupId>com.jianzh5</groupId>
  3. <artifactId>cloud-rocket-starter</artifactId>
  4. </dependency>

3.3.2 自定义配置

  1. rocketmq:
  2. ...
  3. enhance:
  4. # 启动隔离,用于激活配置类EnvironmentIsolationConfig
  5. # 启动后会自动在topic上拼接激活的配置文件,达到自动隔离的效果
  6. enabledIsolation: true
  7. # 隔离环境名称,拼接到topic后,topic_dev,默认空字符串
  8. environment: dev

3.3.3 发送消息

  1. @RestController
  2. @RequestMapping("enhance")
  3. @Slf4j
  4. public class EnhanceProduceController {
  5. //注入增强后的模板,可以自动实现环境隔离,日志记录
  6. @Setter(onMethod_ = @Autowired)
  7. private RocketMQEnhanceTemplate rocketMQEnhanceTemplate;
  8. private static final String topic = "rocket_enhance";
  9. private static final String tag = "member";
  10. /**
  11. * 发送实体消息
  12. */
  13. @GetMapping("/member")
  14. public SendResult member() {
  15. String key = UUID.randomUUID().toString();
  16. MemberMessage message = new MemberMessage();
  17. // 设置业务key
  18. message.setKey(key);
  19. // 设置消息来源,便于查询
  20. message.setSource("MEMBER");
  21. // 业务消息内容
  22. message.setUserName("Java日知录");
  23. message.setBirthday(LocalDate.now());
  24. return rocketMQEnhanceTemplate.send(topic, tag, message);
  25. }
  26. }

注意这里使用的是封装后的模板工具类,一旦在配置文件中启动环境隔离,则生产者的消息也自动发送到隔离后的topic中。

3.3.4 消费者

  1. @Slf4j
  2. @Component
  3. @RocketMQMessageListener(
  4. consumerGroup = "enhance_consumer_group",
  5. topic = "rocket_enhance",
  6. selectorExpression = "*",
  7. consumeThreadMax = 5 //默认是64个线程并发消息,配置 consumeThreadMax 参数指定并发消费线程数,避免太大导致资源不够
  8. )
  9. public class EnhanceMemberMessageListener extends EnhanceMessageHandler<MemberMessage> implements RocketMQListener<MemberMessage> {
  10. @Override
  11. protected void handleMessage(MemberMessage message) throws Exception {
  12. // 此时这里才是最终的业务处理,代码只需要处理资源类关闭异常,其他的可以交给父类重试
  13. System.out.println("业务消息处理:"+message.getUserName());
  14. }
  15. @Override
  16. protected void handleMaxRetriesExceeded(MemberMessage message) {
  17. // 当超过指定重试次数消息时此处方法会被调用
  18. // 生产中可以进行回退或其他业务操作
  19. log.error("消息消费失败,请执行后续处理");
  20. }
  21. /**
  22. * 是否执行重试机制
  23. */
  24. @Override
  25. protected boolean isRetry() {
  26. return true;
  27. }
  28. @Override
  29. protected boolean throwException() {
  30. // 是否抛出异常,false搭配retry自行处理异常
  31. return false;
  32. }
  33. @Override
  34. protected boolean filter() {
  35. // 消息过滤
  36. return false;
  37. }
  38. /**
  39. * 监听消费消息,不需要执行业务处理,委派给父类做基础操作,父类做完基础操作后会调用子类的实际处理类型
  40. */
  41. @Override
  42. public void onMessage(MemberMessage memberMessage) {
  43. super.dispatchMessage(memberMessage);
  44. }
  45. }

为了方便消费者对RocketMQ中的消息进行处理,我们可以使用EnhanceMessageHandler来进行消息的处理和逻辑的处理。

消费者实现了RocketMQListener的同时,可以继承EnhanceMessageHandler来进行公共逻辑的处理,而核心业务逻辑需要自己实现handleMessage方法。 如果需要对消息进行过滤或者去重的处理,则可以重写父类的filter方法进行实现。这样可以更加方便地对消息进行处理,减轻开发者的工作量。

以上,就是今天的主要内容,希望对你有所帮助!

原文链接:https://www.cnblogs.com/jianzh5/p/17301690.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号