SpringBoot集成RocketMQ实现延迟消息

首先导入依赖

<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

application.yml

rocketmq:
  name-server: 127.0.0.1:9876
  producer: #生产者
    group: drunkard #指定发送者组名
    send-message-timeout: 30000 #发送消息超时时间,单位:毫秒。默认为 3000

实时消息

@Autowired
private RocketMQTemplate rocketMQTemplate;

String topic="rocket-topic-01";
rocketMQTemplate.send(topic, MessageBuilder.withPayload("ok").build());

延时消息

	//第一种延时消息
	/**
     * 发送延时消息
     * 延时等级1到16分别表示 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h,3表示延迟10s发送
     * /
	rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload("ok").build(), 15000, 3);


	//第二种手动设置延时消息
	try {
            //先创建producer对象
            DefaultMQProducer producer = new DefaultMQProducer("my-rocket-topic-01");
            // 设置连接地址
            producer.setNamesrvAddr("127.0.0.1:9876");
            //启动producer对象
            producer.start();
            //发送的消息
            String a = "{name:'青莳',price:200.00}";
            //创建消息
            Message msg = new Message("rocket-topic-01", "tmTag", a.getBytes());
            //设置消息延时
            // 1  2  3    4    5  6  7   8   9  10  11 12 13  14  15  16  17  18
            // 1s 5s 10s  30s  1m 2m 3m  4m 5m  6m  7m 8m 9m 10m  20m  30m 1h  2h
            msg.setDelayTimeLevel(3);
            try {
                //发送消息
                SendResult send = producer.send(msg);
                System.out.println(send);
                //关闭
                producer.shutdown();
            } catch (RemotingException | MQBrokerException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        } catch (MQClientException e) {
            throw new RuntimeException(e);
        }
    }

消息消费者

@Component
@RocketMQMessageListener(topic = "rocket-topic-01",consumerGroup = "my-rocket-topic-01")
public class Consumer implements RocketMQListener<String> {
    @Override
    public void onMessage(String s) {
        System.out.println("接收到消息----"+s);
    }
}

延时等级时间修改

需要修改/conf/broker.conf配置文件

brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUSH
messageDelayLevel = 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h

你可能感兴趣的:(spring,boot,java-rocketmq,rocketmq)