springboot整合rocketmq

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 #nameserver地址
  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);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值