1. 程式人生 > 實用技巧 >RocketMQ下載、安裝、以及結合Springboot的使用

RocketMQ下載、安裝、以及結合Springboot的使用

下載

wget https://archive.apache.org/dist/rocketmq/4.5.1/rocketmq-all-4.5.1-bin-release.zip

安裝

unzip rocketmq-all-4.5.1-bin-release.zip

啟動

cd rocketmq-all-4.5.1-bin-release/bin

啟動nameServer、並驗證

nohup sh mqnamesrv &

tail -f ~/logs/rocketmqlogs/namesrv.log

# 如果成功啟動,能看到類似如下的日誌:
2019-07-18 17:03:56 INFO main - The Name Server boot success. ...

啟動Broker 並驗證 (如果啟動失敗,調整記憶體引數)

nohup sh mqbroker -n localhost:9876 autoCreateTopicEnable=true &

tail -f ~/logs/rocketmqlogs/broker.log

# 如果啟動成功,能看到類似如下的日誌:
2019-07-18 17:08:41 INFO main - The broker[itmuchcomdeMacBook-Pro.local, 192.168.43.197:10911] boot success. serializeType=JSON and name server is localhost:9876

關閉MQ

sh mqshutdown namesrv


注意

如果一直報錯 172.17.0.11:10911 連線失敗,需要新增ip配置檔案並指定

brokerIP1=81.68.144.150

nohup sh mqbroker -n 172.17.0.11:9876 autoCreateTopicEnable=true -c conf/broker.conf &

實戰

pom依賴

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

  

傳送訊息

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${pet.topic.order}")
    private String orderTopic;

    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void send() {
        rocketMQTemplate.syncSendOrderly(orderTopic, "這是一條MQ訊息", UUID.randomUUID().toString());
        log.info("MQ傳送訊息成功");
    }

  

接收訊息

package agatha.pet.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author oak
 * @date 2021/1/11
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "pet_group", topic = "${pet.topic.order}")
public class OrderConsumer implements RocketMQListener<String> {

    @Override
    public void onMessage(String msg) {
        log.info("MQ.order.msg:{}", msg);
    }

}