阅读文本大概需要3分钟。
0x01:pom.xml文件引入
代码语言:javascript复制<!--add dependency in pom.xml-->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>${RELEASE.VERSION}</version>
</dependency>
具体版本号:
代码语言:javascript复制https://mvnrepository.com/artifact/org.apache.rocketmq/rocketmq-spring-boot-starter
0x02:修改配置文件application.properties
代码语言:javascript复制rocketmq.name-server=127.0.0.1:9876
rocketmq.producer.group=my-group
配置中的127.0.0.1:9876根据具体情况修改成实际的RocketMQ的NameServer地址与端口
0x03:消息生产者
代码语言:javascript复制@Service
public class ProducerService{
@Resource
private RocketMQTemplate rocketMQTemplate;
public void sendMessage(String message) throws Exception {
//send message synchronously
rocketMQTemplate.convertAndSend("test-topic", message);
}
}
0x04:消息消费者
代码语言:javascript复制@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启动类
代码语言:javascript复制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:测试用例
代码语言:javascript复制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");
}
}
代码语言:javascript复制官网:https://github.com/apache/rocketmq-spring