Springboot快速集成阿里云RocketMq

前言

随着互联网的兴起,越来越多的用户开始享受科技带来的便利,对于服务的压力也日益增大,随即便有了高并发、高性能、高可用等各种解决方案,这里主要介绍RocketMq的集成方法。(文末附源码地址)

正文

1、添加依赖

复制代码
<!-- RocketMQ依赖 -->
<dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>ons-client</artifactId>
    <version>1.8.4.Final</version>
</dependency>

2、添加RocketMq配置

复制代码
## 阿里RocketMQ配置
rocketmq:
  ## 连接点地址 参考控制台实例详情
  name-server: xxx.rmq.aliyuncs.com:8080
  access-key: xxx
  secret-key: xxx
  ## 自行在阿里云控制台添加group和topic
  group: test_group
  topic: test_topic

配置类:

复制代码
@Data
@Configuration
@ConfigurationProperties(prefix = "rocketmq")
public class RocketMqConfig {

    private String nameServer;

    private String accessKey;

    private String secretKey;

    @Bean
    public Properties build() {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.AccessKey, accessKey);
        properties.setProperty(PropertyKeyConst.SecretKey, secretKey);
        properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, nameServer);
        return properties;
    }

}

3、生产端代码(配置+发送消息)

复制代码
    @Autowired
    RocketMqConfig rocketMqConfig;

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

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ProducerBean buildProducer() {
        ProducerBean producer = new ProducerBean();
        //配置文件
        Properties properties = rocketMqConfig.build();
        //设置发送超时时间,单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
        //设置组id
        properties.setProperty(PropertyKeyConst.GROUP_ID, group);
        producer.setProperties(properties);
        return producer;
    }
复制代码
    public void sendAsyncMessage(String content, String topic) {
        Message msg = new Message();
        //设置主题和标签
        msg.setTopic(topic);
        msg.setTag("*");
        msg.setBody(content.getBytes());
        producer.sendAsync(msg, new SendAsyncMessage());
    }

4、消费端代码(配置+接收消息)

复制代码
@Configuration
public class ConsumerClient {

    @Value("${rocketmq.group}")
    private String group;
    @Value("${rocketmq.topic}")
    private String topic;

    @Autowired
    RocketMqConfig rocketMqConfig;
    @Autowired
    private MyRocketMessageListener messageListener;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean buildConsumer() {

        //消费者对象bean
        ConsumerBean consumerBean = new ConsumerBean();
        //配置文件
        Properties properties = rocketMqConfig.build();
        //设置组id
        properties.setProperty(PropertyKeyConst.GROUP_ID, group);
        //将消费者线程数固定为20个 20为默认值
//        properties.setProperty(PropertyKeyConst.ConsumeThreadNums, threadNum);
        consumerBean.setProperties(properties);

        //配置订阅关系
        Map<Subscription, MessageListener> subscriptionTable = new HashMap<>();
        //当前为订阅一个主题配置(订阅多个topic一样设置)
        Subscription subscription = new Subscription();
        subscription.setTopic(topic);
        subscription.setExpression("*");
        subscriptionTable.put(subscription, messageListener);
        consumerBean.setSubscriptionTable(subscriptionTable);
        return consumerBean;
    }
}
复制代码
@Slf4j
@Configuration
public class MyRocketMessageListener implements MessageListener {


    @Override
    public Action consume(Message message, ConsumeContext context) {

        // 业务处理逻辑
        log.info(">>>>> 【消费者】系统时间:[{}]接收消息MsgId=[{}],消息内容:{}", LocalDateTime.now(), message.getMsgID(), new String(message.getBody(), StandardCharsets.UTF_8));
        try {
            // todo 业务逻辑处理
            return Action.CommitMessage;
        } catch (Exception e) {
            //消费失败
            log.error(">>>>> 【消费者】系统时间:[{}]处理消息MsgId=[{}], 当前消费失败, 开始重试......!", LocalDateTime.now(), message.getMsgID());
            return Action.ReconsumeLater;
        }
    }
}

5、接口

复制代码
@RestController
@RequestMapping("test")
public class MqTest {

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

    @Autowired
    RocketMQUtil rocketMQUtil;

    @RequestMapping("mq")
    public String testMq(@RequestParam("content") String content) {
        rocketMQUtil.sendAsyncMessage(content, topic);
        return "success";
    }

}

6、测试验证

①启动项目

②调用接口

浏览器:http://localhost:8080/test/mq?content=testPush

观察后端日志:

至此,接入完成。

附:

源码地址**:** https://gitee.com/yhc910/RocketMq-Demo

相关推荐
qq_297574672 天前
RocketMQ系列文章(入门篇第6篇):延时消息+顺序消息实战
spring boot·rocketmq·java-rocketmq
逍遥德3 天前
Java 锁(线程间)和数据库锁(事务间)对比详解
java·数据库·sql·高并发·锁机制
如来神掌十八式4 天前
web高并发访问只能增加服务实例吗
高并发
刘~浪地球6 天前
消息队列--RocketMQ 架构设计与优化
架构·rocketmq
Flying pigs~~6 天前
检索增强生成RAG项目tools_04:flask➕fastapi➕高并发
数据库·python·flask·大模型·fastapi·异步
qq_283720056 天前
Python GIL 底层实现与高并发突破实战
python·性能优化·高并发·全局锁
切糕师学AI7 天前
深入浅出 协程(Coroutine):从原理到实践
高并发·协程·异步·async/await·coroutine·并发编程模型
2401_892070988 天前
【Linux C++ 后端实战】异步日志系统 AsyncLogging 完整设计与源码解析
linux·c++·高并发·异步日志
Rick19938 天前
rabbitmq, rocketmq, kafka这三种消息如何分别保住可靠性,顺序性,以及应用场景?
kafka·rabbitmq·rocketmq
有梦想的小何8 天前
从0到1搭建可靠消息链路:RocketMQ重试 + Redis幂等实战
java·redis·bootstrap·rocketmq