RocketMQ篇四 springboot集成RocketMQ

1、加依赖

        
            org.apache.rocketmq
            rocketmq-spring-boot-starter
            2.0.3
        

注:以前的那个要注释掉


    
    
    

2、构建消息体

@Data
@Accessors(chain = true)
public class TestMessaging {
    /**
     * 消息id
     */
    private String msgId;
    /**
     * 消息内容
     */
    private String msgText;
}

3、生产者

@RestController
public class TestController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
 
    /**
     * 普通消息投递
     * 请求接口http://127.0.0.1:8089/test?msg=asdkfjsdakfj大師傅
     */
    @GetMapping("/test")
    public String test(String msg) {
        System.out.println("laidaozheli");
        TestMessaging testMessaging = new TestMessaging()
                .setMsgId(UUID.randomUUID().toString())
                .setMsgText(msg);
        rocketMQTemplate.convertAndSend("add-bonus", testMessaging);
        return "投递消息 => " + msg + " => 成功";
    }
}

4、消费者

@Slf4j
@Service
// topic 主题要与消息生产者一致
@RocketMQMessageListener(consumerGroup = "springboot-rocketmq-group", topic = "add-bonus")
public class AddBonusListener implements RocketMQListener {
    @Override
    public void onMessage(TestMessaging testMessaging) {
        log.warn("消费到消息 => "+testMessaging.toString());
    }
}

5、配置文件加两个选项


rocketmq.producer.group=springboot-rocketmq-group

#没有下面这个,会报错bean of type 'org.apache.rocketmq.spring.core.RocketMQTemplate' that could not be found.
rocketmq.name-server=127.0.0.1:9876

其他参考文章:springboot中rocketmq的集成与使用 | W pit

你可能感兴趣的:(rocketmq,rocketmq)