第十八章:springboot 整合阿里云 rocketMQ

一、rocketMQ简介

消息队列 RocketMQ 是阿里巴巴集团自主研发的专业消息中间件。 产品基于高可用分布式集群技术,提供消息订阅和发布、消息轨迹查询、定时(延时)消息、资源统计、监控报警等一系列消息云服务,是企业级互联网架构的核心产品。 消息队列 RocketMQ 历史超过9年,为分布式应用系统提供异步解耦、削峰填谷的能力,同时具备海量消息堆积、高吞吐、可靠重试等互联网应用所需的特性,是阿里巴巴双11使用的核心产品。

 

二、rocketMQ的使用

打开阿里云产品,找到 rocketMQ

9aa29c73ac6b423fd19aa64dedb1fbf8c4d.jpg

 

这里需要我们根据需要开通包年还是包月服务,开通成功后进入控制台

acff10ce8f0b7241a3f07dd1706b2f2e15c.jpg

根据提示创建实例、创建Topics、创建Group

afad46d0464e57081698a8ba2414d59d06e.jpg

864a8b5d5737fb49bf93862e4d28d7e93ce.jpg

0cf3a03eb392810dca418453188e021ae8d.jpg

创建好了之后,打开 Topic 管理,手动发送一条消息

30907cdd11a8b6d42394d2453971c49181e.jpg

可以看到发送成功后会返回信息的 messageID

 

三、整合 springboot

首先引入 pom 

<!--消息队列 RocketMQ-->
<dependency>
   <groupId>com.aliyun.openservices</groupId>
   <artifactId>ons-client</artifactId>
   <version>1.7.9.Final</version>
</dependency>

定义 rocketMQ 配置

@Configuration
public class RocketMQConfig {


    public Properties getProperties(){

        Properties properties=new Properties();
        /**
         * 键的首字母必须大写
         */
        properties.setProperty("AccessKey","**");
        //
        properties.setProperty("SecretKey","**");
        //
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
        // 顺序消息消费失败进行重试前的等待时间,单位(毫秒)
        properties.put(PropertyKeyConst.SuspendTimeMillis, "100");
        // 消息消费失败时的最大重试次数
        properties.put(PropertyKeyConst.MaxReconsumeTimes, "20");
        //
        properties.put(PropertyKeyConst.NAMESRV_ADDR, "http://MQ_INST_1944503281593155_BaOTPbFU.mq-internet-access.mq-internet.aliyuncs.com:80");
        return  properties;
    }
}

AccessKey、SecretKey 可在阿里云个人信息中找到

NAMESRV_ADDR  是实例的接入点

9c9a061c8370691617a1b5ddffb1792f503.jpg

 

定义消息发送者

@Component
public class RocketMQProducer {
    @Autowired
    private RocketMQConfig rocketMQConfig;

    /**
     * 1、发送普通消息
     *
     * @param message
     * @return
     */
    public boolean sendNormalMessage(Message message,String groupId) {

        Properties properties=rocketMQConfig.getProperties();
        properties.setProperty(PropertyKeyConst.GROUP_ID,groupId);
        Producer producer = ONSFactory.createProducer(properties);
        // 在发送消息前,必须调用 start 方法来启动 Producer,只需调用一次即可
        producer.start();
        try {
            SendResult sendResult = producer.send(message);
            // 同步发送消息,只要不抛异常就是成功
            if (sendResult != null) {
                System.out.println("消息发送成功:messageID:"+sendResult.getMessageId());
                return true;
            }
        } catch (Exception e) {
            // 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理
            e.printStackTrace();
        }
        return false;
    }
}

定义消息消费者

@Component
public class RocketMQConsumer {

    @Autowired
    private RocketMQConfig rocketMQConfig;


    /**
     * 1、普通订阅
     *
     * @param
     */
    public void normalSubscribe( ) {

        Properties properties = rocketMQConfig.getProperties();

        properties.put(PropertyKeyConst.GROUP_ID, "GID-test");

        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe("test", "*", new MessageListener() {
            @Override
            public Action consume(Message message, ConsumeContext context) {
                System.out.println("Receive: " + new String(message.getBody()));

                    //把消息转化为java对象
                    //JSONObject jsonObject=JSONObject.parseObject(jsonString);
                    //Book book= jsonObject.toJavaObject(Book.class);

                return Action.CommitMessage;
            }
        });

        consumer.start();
    }
}

测试类

	@Autowired
	private RocketMQProducer rocketMQProducer;

	@Autowired
	private RocketMQConsumer rocketMQConsumer;

    //发送信息
	@RequestMapping("/send")
	public String send(String msg){
        // test 是创建的topic是名称, tag 是消息的二级分类,可以填空
		Message message=new Message("test","tag",msg.getBytes());
        // GID-test 是 发送信息组ID
		rocketMQProducer.sendNormalMessage(message,"GID-test");
		return "ok";
	}


    //接收信息
	@RequestMapping("/receive")
	public String receive(){
		rocketMQConsumer.normalSubscribe();
		return "ok";
	}

启动项目,访问 send 和 receive,控制台打印如下


消息发送成功:messageID:C0A83292361818B4AAC23C548787000F
Receive: 测试

到这里说明整合成功。最后我们只需要在启动项目的时候启动消费者。spring 监听器可以实现,或者可以通过实现接口 CommandLineRunner 

@Component
public class RocketConsumerListener implements CommandLineRunner {

    @Autowired
    private RocketMQConsumer rocketMQConsumer;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("========rocketMQ消费者启动==========");
        rocketMQConsumer.normalSubscribe();
    }
}

这样在启动项目的时候消费者也被启动。到此springboot和rocketMQ的整合就完成啦。

 

转载于:https://my.oschina.net/u/3387320/blog/3009452

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值