springboot集成rocketmq

  本文是springboot集成rocketmq的入门篇,主要介绍单机环境下安装rocketmq,并集成到springboot框架中,实现字符串类型消息的生产和消费。
  1)高可用集群部署方案请参考 待更新。。。
  2)更多使用方式请参考 待更新。。。

一、下载、安装、启动

1、下载
http://rocketmq.apache.org/dowloading/releases/

2、安装
已rocketmq-all-4.6.0-source-release.zip为例

unzip rocketmq-all-4.6.0-source-release.zip
cd rocketmq-all-4.6.0-source-release
mvn -Prelease-all -DskipTests clean install -U
cd distribution/target/rocketmq-4.6.0/rocketmq-4.6.0

注:target目录看起来有些奇怪,不用管具体差异,找到里面的
rocketmq-4.6.0文件夹可以放到任意指定未知
3、配置环境变量
/etc/profile

export ROCKETMQ_HOME=/Users/zhanghao/Desktop/develop/rocketmq-4.6.0
export PATH=$PATH:$ROCKETMQ_HOME/bin

4、启动NameServer
  进入bin目录,当然环境变量已经配置了PATH的话可以直接运行,此处只是最简单的启动,采用所有的默认配置,下述Broker也采用默认配置。
默认端口:9876

nohup sh mqnamesrv &

5、启动Broker
默认端口:10911

nohup sh mqbroker -n localhost:9876 &

6、创建测试Topic

sh mqadmin updateTopic -b localhost:10911 -n localhost:9876 -t my-topic

  -b Broker地址
  -n NameServer地址
  -t Topic名称

二、SpringBoot集成

1、pom.xml

<dependency>
	<groupId>org.apache.rocketmq</groupId>
	<artifactId>rocketmq-spring-boot-starter</artifactId>
	<version>2.0.4</version>
</dependency>

2、application.properties

# 生产者配置
rocketmq.name-server=localhost:9876
rocketmq.producer.group=my-group1
rocketmq.producer.sendMessageTimeout=300000
# 消费者配置
#rocketmq.name-server=localhost:9876

3、生产者

package com.houzigege.rocketmq;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class ProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/send")
    public String testSend(String msg) {
        try {
            rocketMQTemplate.convertAndSend("my-topic", msg);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }
}

4、消费者

package com.houzigege.rocketmq;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = "my-topic", consumerGroup = "string_consumer")
public class StringConsumeListener implements RocketMQListener<String> {
    @Override
    public void onMessage(String message) {
        System.out.println("------- StringConsumer received: " + message);
    }
}

参考:
http://rocketmq.apache.org/docs/quick-start/
https://github.com/apache/rocketmq-spring/tree/master/rocketmq-spring-boot-samples

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页