首頁 > 軟體

SpringBoot整合RocketMQ的方法詳解

2022-08-12 18:01:22

一:Ubuntu安裝RocketMQ

1.下載(在下面地址選擇自己需要的版本的rocketmq)

http://rocketmq.apache.org/release_notes/

2.解壓,更改設定

將下載的zip檔案解壓到自己需要安裝的位置

在unbuntu系統下需要修改安裝跟目錄下的兩個檔案

bin/runserver.sh  和  bin/runbroker.sh  檔案

(1).都修改兩個檔案的  java_home=/java安裝HOME路徑/

(2).都修改兩個檔案的  java_home=/java安裝HOME路徑/jre/

(3).修改runserver.sh記憶體         

JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn2g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"
 
# 原來是:JAVA_OPT="${JAVA_OPT} -server -Xms4g -Xmx4g -Xmn4g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"

(4).修改runbroker.sh記憶體        

JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g   
# 原來是:JAVA_OPT="${JAVA_OPT} -server -Xms8g -Xmx8g 

(5).建立紀錄檔目錄 

mkdir logs

3.後臺掛載啟動 mqnamesrv(在安裝根目錄下執行)

nohup sh bin/mqnamesrv > logs/namesrv.log 2>&1 &

5.檢視mqnamesrv是否啟動成功

檢視 logs/namesrv.log  檔案出現以下提示表示啟動成功!

The Name Server boot success. serializeType=JSON

6.安裝 mqbroker

Broker是 RocketMQ 的核心,大部分'重量級'工作都是由 Broker完成的,

包括接收 Producer 發過來的訊息、處理 Consumer 的消費訊息請求、訊息的持 久化儲存、訊息的 HA 機制以及伺服器端過濾功能等 。

(1).更改broker設定,在安裝根目錄下conf/broker.conf檔案 新增一行    

brokerIP1 = 127.0.0.0
# IP根據自己電腦伺服器修改一下,最好不要使用這個,ifconfig就可以檢視到自己伺服器的IP

(2).掛載啟動 mqbroker(在安裝根目錄下)

nohup sh bin/mqbroker -c conf/broker.conf -n localhost:9876 > logs/broker.log 2>&1 &

(3).檢視 mqbroker 是否啟動成功

檢視  logs/broker.log  檔案出現以下提示表示啟動成功!   

The broker[broker-a, 127.0.0.0:10911] boot success. serializeType=JSON and name server is localhost:9876

7.關閉broker和nameserver(在安裝根目錄下執行)

./bin/mqshutdown broker
./bin/mqshutdown namesrv

8.建立一個topic  

./bin/mqadmin updateTopic -n '127.0.0.0:9876' -c MyCluster -t MyTopic

9.檢視叢集狀態  

./bin/mqadmin clusterList -n localhost:9876

二:新增RocketMQ依賴

<!--rocket mq 依賴-->
<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-spring-boot-starter</artifactId>
    <version>2.1.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </exclusion>
    </exclusions>
</dependency>

三:在application中新增RocketMQ設定

#rocketmq 設定
rocketmq:
  name-server: 127.0.0.0:9876 #IP根據自己電腦伺服器設定的 mqbroker->brokerIP1 修改一下,最好不要使用這個
  producer:
    group: rocketmq_group
 
myrocketmq-config:
  my-topic: rocketmq_topic
  my-consumer-group: rocketmq_group_consumer

四:編寫消費者,訊息生產者,訊息實體類(自定義)

//Rocket消費者
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${myrocketmq-config.my-consumer-group}", topic = "${myrocketmq-config.my-topic}")
public class RocketConsumer implements RocketMQListener<RocketmqVo> {
 
    @Override
    public void onMessage(RocketmqVo rocketmqVo) {
        log.info("收到RocketMQ訊息:{}",rocketmqVo);
    }
}
//Rocket生產者
@Slf4j
@Component
public class RocketProduce {
 
    @Value("${myrocketmq-config.my-topic}")
    private String mqTopic;
    @Value("${myrocketmq-config.my-consumer-group}")
    private String mqConsumerGroup;
    @Autowired
    private RocketMQTemplate mqTemplate;
 
    /**
     * 同步傳送
     *
     * @param title 傳送訊息
     * @param data  訊息內容
     */
    public void sync(String title, Object data) {
        String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
        RocketmqVo rocketmqVo = new RocketmqVo(mqConsumerGroup, mqTopic, title, time, data);
        SendResult sendResult = mqTemplate.syncSend(mqTopic, rocketmqVo);
        log.info("同步傳送:{}", rocketmqVo);
        log.info("同步傳送訊息結果:{}", sendResult);
    }
 
    /**
     * 非同步傳送
     *
     * @param title 傳送訊息
     * @param data  訊息內容
     */
    public void async(String title, Object data) {
        String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
        RocketmqVo rocketmqVo = new RocketmqVo(mqConsumerGroup, mqTopic, title, time, data);
        log.info("非同步傳送:{}", rocketmqVo);
        mqTemplate.asyncSend(mqTopic, rocketmqVo, new SendCallback() {
            @Override
            public void onSuccess(SendResult var1) {
                log.info("非同步傳送成功:{}", var1);
            }
 
            @Override
            public void onException(Throwable var1) {
                log.info("非同步傳送失敗:{}", var1.getMessage());
            }
        });
    }
 
    /**
     * 單向傳送
     *
     * @param title 傳送訊息
     */
    public void oneway(String title, Object data) {
        String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
        RocketmqVo rocketmqVo = new RocketmqVo(mqConsumerGroup, mqTopic, title, time, data);
        mqTemplate.sendOneWay(mqTopic, rocketmqVo);
        log.info("單向傳送:{}", rocketmqVo);
    }
}
//Rocket訊息實體
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class RocketmqVo {
 
    @Value("${myrocketmq-config.my-consumer-group}")
    private String group;
 
    @Value("${myrocketmq-config.my-topic}")
    private String topic;
 
    private String title;
 
    private String date;
 
    private Object data;
 
 
    public RocketmqVo(String title, String date, Object data) {
        this.title = title;
        this.date = date;
        this.data = data;
    }
}

五:測試Controller

@RestController
@RequestMapping("/mqtest")
public class RocketController {
 
    @Resource
    private RocketProduce producer;
 
    @RequestMapping("/sendMessageSync/{msg}")
    public String sendMessageSync(@PathVariable("msg") String message) {
        producer.sync(message, null);
        return "訊息傳送完成";
    }
 
    @RequestMapping("/sendMessageAsync/{msg}")
    public String sendMessageAsync(@PathVariable("msg") String message) {
        producer.async(message, null);
        return "訊息傳送完成";
    }
 
    @RequestMapping("/sendMessageOneway/{msg}")
    public String sendMessageOneway(@PathVariable("msg") String message) {
        producer.oneway(message, null);
        return "訊息傳送完成";
    }
}

以上就是SpringBoot整合RocketMQ的方法詳解的詳細內容,更多關於SpringBoot整合RocketMQ的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com