搭建好RocketMQ,使用SpringBoot项目
引入依赖
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
配置application.yml
spring:
application:
name: springboot-rocketmq
rocketmq:
name-server: http://192.168.80.246:9877
producer:
group: boot_producer_group
send-message-timeout: 30000
创建生产者类 ProducerComponent
,可以根据每条来进行发送测试
@Component
@Slf4j
public class ProducerComponent {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@Value("${rocketmq.producer.send-message-timeout}")
private Integer messageTimeOut;
@PostConstruct
public void test(){
log.info("消息启动!");
// 如下三种方式等价,第二种加入key,第三种是另一种方式加入key
//rocketMQTemplate.convertAndSend("test-topic-1", "Hello, World!");
//rocketMQTemplate.send("test-topic-1",MessageBuilder.withPayload("Hello, World! I'm from spring message").setHeader(RocketMQHeaders.KEYS,"67").build());
//rocketMQTemplate.convertAndSend("test-topic-1","Hello, World!", Collections.singletonMap(RocketMQHeaders.KEYS, "pumpkin"));
// topic: ORDER,tag: paid, cacel
//rocketMQTemplate.convertAndSend("ORDER:paid", "Hello, World!");
//rocketMQTemplate.convertAndSend("ORDER:cancel", "Hello, World1!");
//test-topic-1 主题 | tag1 标签 | pumpkin key
//rocketMQTemplate.convertAndSend("test-topic-1:tag1","Hello, World!", Collections.singletonMap(RocketMQHeaders.KEYS, "pumpkin"));
//消息体为自定义对象
//rocketMQTemplate.convertAndSend("test-topic-2", new User("T_001", "address",1));
// 发送延迟消息,5代表1m(分钟)
//在start版本中 延时消息一共分为18个等级分别为:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
//rocketMQTemplate.syncSend("test-topic-1:delay",MessageBuilder.withPayload("11111").build(),messageTimeOut,5);
// 发送即发即失消息(不关心发送结果)
//rocketMQTemplate.sendOneWay("test-topic-1:onway", MessageBuilder.withPayload("I'm one way message").build());
//发送顺序消息,根据key选择队列。例如:orderId,productId
//rocketMQTemplate.syncSendOrderly("test-topic-1:order", "I'm order message", "1234");
// 发送异步消息
rocketMQTemplate.asyncSend("test-topic-1:async111777", MessageBuilder.withPayload("I'm one async messag111e").build(), new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.println("发送成功");
}
@Override
public void onException(Throwable throwable) {
System.out.println("发送失败");
}
});
}
@Data
@AllArgsConstructor
class User{
private String name;
private String address;
private Integer age;
}
}
创建消费者
@Component
@RocketMQMessageListener(topic = "test-topic-1", consumerGroup = "my-consumer_test-topic-1",consumeMode = ConsumeMode.ORDERLY)
@Slf4j
public class ConsumerComponent implements RocketMQListener<String>{
@Autowired
private RocketMQTemplate rocketMQTemplate;
@Override
public void onMessage(String message) {
log.info("received message: " + message);
}
}
说明:SpringBoot启动后,生产者和消费者也会随之启动,发送和接收消息,如果消费者抛出异常,消息会重新进入RocketMQ进行消费。
结语
一名四年工作经验的程序猿,目前从事物流行业的工作,有自己的小破网站amoqi.cn。欢迎大家关注公众号【CoderQi】,一起来交流JAVA知识,包括但不限于SpringBoot+微服务,更有奇奇学习过程中学习的视频、面试资料和专业书籍等免费放送,希望大家能够喜欢。