SprinBoot整合RocketMQ

本地仓库安装

rocketmq-spring-boot-starter的依赖包是不能直接从中央仓库下载的,需要自己通过源码install到本地仓库的

#源码地址
https://github.com/apache/rocketmq-spring
#进入源码目录,执行如下命令
mvn clean install

下载是注意一下版本问题,选择2.0.0的,不同版本配置不一样。


image.png

或者百度云
链接:https://pan.baidu.com/s/1ngF8qVLRJtcnMZcSMWi_kQ
提取码:jzd0

这样说明安装成功


image.png

编写application.properties配置文件

spring.application.name = spring-rocketmq
spring.rocketmq.nameServer=192.168.31.150:9876
spring.rocketmq.producer.group=my-group

生产者发送消息

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SpringProducer {

    // 注入rocketMQ的模板
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送消息
     *
     * @param topic
     * @param msg
     */
    public void sendMsg(String topic, String msg) {
        this.rocketMQTemplate.convertAndSend(topic, msg);
    }

}

消费消息

import org.apache.rocketmq.spring.annotation.ConsumeMode;
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 = "my-group",
        selectorExpression = "*"
)
public class SpringConsumer implements RocketMQListener {

    @Override
    public void onMessage(String msg) {
        System.out.println("接收到消息 -> " + msg);
    }
}

编写启动类

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

@SpringBootApplication
public class MyApplication {

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

编写测试用例

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 SpringProducer springProducer;

    @Test
    public void testSendMessage() {
        springProducer.sendMsg("my-topic","为什么不打印");
    }

}

测试

先启动springboot,再运行测试用例,即可看到消费者接收到生产者发送的消息。

你可能感兴趣的:(SprinBoot整合RocketMQ)