消息中间件学习三--RocketMQ和Springboot

1.Spring Boot中快速集成RocketMQ

   第一步:引进依赖   

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

 

  第二步:.yml文件配置     

rocketmq:
  name-server: 127.0.0.1:9876;127.0.0.2:9876
  producer:
    group: xht-group
    access-key: rocketmq
    secret-key: 12345678

第三步:java创建生产者

 

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@Slf4j
@RestController
public class ScheduledMessageProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;


    @RequestMapping(value = "send")
    public String send(String msg, int level){
        //普通消息发送
        rocketMQTemplate.convertAndSend("delay-message-test", msg);
        Message<String> message = new GenericMessage<>(msg);
        //延时消息发送,level对应的默认延时时间依次为1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        rocketMQTemplate.syncSend("delay-message-test",message,1000, level);
        log.info("消息已发送:{}",msg);
        return "success";
    }

}

注:消息的发送主要通过RocketMQTemplate进行,

       该对象提供了非常多已经封装好的基础方法供调用,

       这里只以普通消息发送,和同步延时消息的发送做为例子。

第四步:java创建消费者  

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "delay-message-test", consumerGroup = "xht-group", accessKey = "rocketmq", secretKey = "12345678")
public class ScheduledMessageConsumer implements RocketMQListener<String> {

    @Override
    public void onMessage(String message) {
        log.info("received message: {}", message);
    }
}

注:消费者端的实现非常简单,配置参数都集中于@RocketMQMessageListener注解上。

 

学习来源:https://www.jianshu.com/p/6d336f25f754

                  https://www.jianshu.com/p/1072d3599ed8

posted @ 2020-09-22 14:37  小窝蜗  阅读(334)  评论(0编辑  收藏  举报