SpringBoot集成RockMQ

阅读文本大概需要3分钟。

0x01:pom.xml文件引入

<!--add dependency in pom.xml-->
<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-spring-boot-starter</artifactId>
    <version>${RELEASE.VERSION}</version>
</dependency>

具体版本号:

https://mvnrepository.com/artifact/org.apache.rocketmq/rocketmq-spring-boot-starter

0x02:修改配置文件application.properties

rocketmq.name-server=127.0.0.1:9876
rocketmq.producer.group=my-group

配置中的127.0.0.1:9876根据具体情况修改成实际的RocketMQ的NameServer地址与端口

0x03:消息生产者

@Service
public class ProducerService{

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessage(String message) throws Exception {
          //send message synchronously
        rocketMQTemplate.convertAndSend("test-topic", message);
    }

}

0x04:消息消费者

@Slf4j
@Service
@RocketMQMessageListener(topic = "test-topic", 
consumerGroup = "my-group")
public class MessageConsumer implements RocketMQListener<String>{
    public void onMessage(String message) {
        log.info("received message: {}", message);
    }
}

0x05:SpringBoot启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MQApplication {

    public static void main(String[] args) {
        SpringApplication.run(MQApplication.class, args);
    }
}

0x06:测试用例

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestSpringRocketMQ {

    @Autowired
    private ProducerService producerService;

    @Test
    public void testSendMessage() {
        producerService.sendMsg("Hello RocketMQ Message");
    }

}
官网:https://github.com/apache/rocketmq-spring

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 精讲Spring&nbsp;Boot—入门+进阶+实例

04 优秀的Java程序员必须了解的GC哪些

05 互联网支付系统整体架构详解

关注我

每天进步一点点

喜欢!在看☟

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章