SpringBoot整合RocketMQ
1. 引入依赖
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>tocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2. 配置RocketMQ
rocketmq:
name-server: localhost:9876
producer:
group: producer_test_group
3. 创建生产者
@RestController
public class ProducerController {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@GetMapping("syncSend")
public String sendMessage(){
rocketMQTemplate.syncSend("topic-test","测试同步消息");
User user = new User();
user.setId("1");
rocketMQTemplate.syncSend("topic-object-test",user);
return "ok";
}
@GetMapping("async")
public void async() {
rocketMQTemplate.asyncSend("topic-test", "测试异步消息", new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.println("异步发送成功");
}
@Override
public void onException(Throwable throwable) {
System.Out.println("异步发送失败");
}
});
}
@GetMapping("oneway")
public void oneway() {
rocketMQTemplate.sendOneWay("topic-test", "测试单向消息");
System.out.println("单向发送");
}
}
4. 创建消费者
@Service
@RocketMQMessageListener(consumerGroup = "consumer-string-group", topic = "topic-test")
public class StringConsumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
System.out.println("消费字符串消息{}", message);
}
}
@Service
@RocketMQMessageListener(consumerGroup = "consumer-object-group", topic = "topic-object-test")
public class ObjectConsumer implements RocketMQListener<User> {
@Override
public void onMessage(User message) {
System.out.println("消费对象消息{}", message);
}
}