阿里云ONS消息队列入门指南

概述

消息队列 RocketMQ 是阿里巴巴集团基于高可用分布式集群技术,自主研发的云正式商用的专业消息中间件,既可为分布式应用系统提供异步解耦和削峰填谷的能力,同时也具备互联网应用所需的海量消息堆积、高吞吐、可靠重试等特性,是阿里巴巴双 11 使用的核心产品

阿里云官方接入文档:https://help.aliyun.com/document_detail/29553.html?spm=a2c4g.11186623.6.570.632b7059ZI0shf

springboot整合接入

pom文件

<dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>ons-client</artifactId>
            <version>1.8.0.Final</version>
        </dependency>

application.yml

mq:
  consumerId: @ons.consumerId@
  accessKeyId: @ons.accessKeyId@
  accessKeySecret: @ons.accessKeySecret@
  onsAddr: @ons.onsAddr@
  automaticPackagingTopic: @ons.automaticPackagingTopic@
  maxReconsumeTimes: @ons.maxReconsumeTimes@

不同的环境中对应不同的properties文件

mq.consumerId=xxx
mq.accessKeyId=xxx
mq.accessKeySecret=xxx
mq.onsAddr=xxx
mq.automaticPackagingTopic=xxx
mq.maxReconsumeTimes=3

在这里插入图片描述

mq消费者

@Component
public class MessageConsumer {

    @Value("${mq.consumerId}")
    private String consumerId;

    @Value("${mq.accessKeyId}")
    private String accessKey;

    @Value("${mq.accessKeySecret}")
    private String secretKey;

    @Value("${mq.onsAddr}")
    private String onsAddr;

    @Value("${mq.automaticPackagingTopic}")
    private String topic;

    @Value("${mq.maxReconsumeTimes}")
    private String maxReconsumeTimes;

    private Consumer consumer;

    private final Map<String, MessageListener> listenerMap =new ConcurrentHashMap<>();

    @Autowired
    private MessageConsumer(Map<String, MessageListener> listenerMap){
        this.listenerMap.clear();
        listenerMap.forEach((k,v)->this.listenerMap.put(v.getType(),v));
    }

    @PostConstruct
    public void init(){
        LogFactory.mqlog.info("Consumer 开始启动...");
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.GROUP_ID, consumerId);
        properties.put(PropertyKeyConst.AccessKey, accessKey);
        properties.put(PropertyKeyConst.SecretKey, secretKey);
        properties.put(PropertyKeyConst.NAMESRV_ADDR, onsAddr);
        properties.put(PropertyKeyConst.MaxReconsumeTimes, maxReconsumeTimes);
        consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(topic,"*", (message,context)->listenerMap.get(message.getTag()).consume(message,context));
        consumer.start();
        LogFactory.mqlog.info("Consumer 启动完成");
    }

}

例如消费两种消息

public interface MessageListener {
    /**
     * 获取listener类型
     * @return
     */
    String getType();

    /**
     *  消费消息
     * @param message
     * @param context
     * @return
     */
    Action consume(final Message message, final ConsumeContext context);
}

一类接收足球消息

@Component
public class FootBallListener implements MessageListener {

    private static final String TAG_FootBall = "TAG_FootBall";
    
    @Override
    public Action consume(Message message, ConsumeContext context) {
        LogFactory.mqlog.info("receive :" + message.toString());

        try {
            // do what u should do
            LogFactory.mqlog.info("consume success");
            return Action.CommitMessage;
        } catch (Exception e) {
            LogFactory.mqlog.error("consume fail:" + e);
            return Action.ReconsumeLater;
        }
    }

    @Override
    public String getType() {
        return TAG_FootBall;
    }
}

接收乒乓球消息

@Component
public class PingPangListener implements MessageListener {

    public static final String TAG_PingPang = "TAG_PingPang";

  
    @Override
    public Action consume(Message message, ConsumeContext context) {
        LogFactory.jvopfLog.info("receive:" + message.toString());
        try {
            //你的业务代码
            if(true){
                LogFactory.mqlog.info("consume Success");
                return Action.CommitMessage;
            }else {//比较重要的消息,失败后重试
                LogFactory.mqlog.info("consume Fail");
                return Action.ReconsumeLater;
            }
        }catch (Exception e){
            LogFactory.mqlog.error("consume Exception:" + e);
            return Action.ReconsumeLater;
        }
    }

    @Override
    public String getType() {
        return TAG_PingPang;
    }
}

mq 生产者

摘自 : https://help.aliyun.com/document_detail/29553.html?spm=a2c4g.11186623.6.570.dc4d2e77x4Y8BP

 package demo;
 import com.aliyun.openservices.ons.api.Message;
 import com.aliyun.openservices.ons.api.Producer;
 import com.aliyun.openservices.ons.api.SendResult;
 import com.aliyun.openservices.ons.api.exception.ONSClientException;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class ProduceWithSpring {
     public static void main(String[] args) {
         /**
          * 生产者 Bean 配置在 producer.xml 中,可通过 ApplicationContext 获取或者直接注入到其他类(比如具体的 Controller)中
          */
         ApplicationContext context = new ClassPathXmlApplicationContext("producer.xml");
         Producer producer = (Producer) context.getBean("producer");
         //循环发送消息
         for (int i = 0; i < 100; i++) {
             Message msg = new Message( //
                     // Message 所属的 Topic
                     "TopicTestMQ",
                     // Message Tag 可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在消息队列 RocketMQ 的服务器过滤
                     "TagA",
                     // Message Body 可以是任何二进制形式的数据, 消息队列 RocketMQ 不做任何干预
                     // 需要 Producer 与 Consumer 协商好一致的序列化和反序列化方式
                     "Hello MQ".getBytes());
             // 设置代表消息的业务关键属性,请尽可能全局唯一
             // 以方便您在无法正常收到消息情况下,可通过控制台查询消息并补发
             // 注意:不设置也不会影响消息正常收发
             msg.setKey("ORDERID_100");
             // 发送消息,只要不抛异常就是成功
             try {
                 SendResult sendResult = producer.send(msg);
                 assert sendResult != null;
                 System.out.println("send success: " + sendResult.getMessageId());
             }catch (ONSClientException e) {
                 System.out.println("发送失败");
             }
         }
     }
 }
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、MQ场景     1)订单异步解耦     2)解决分布式事务问题     3)应用于聊天平台     4)大规模机器的Cache同步     5)MySQL BinLog订阅数据分发 2、ONS应用场景     异步、解耦、最终一致、并行 3、设计假定     1)每台PC机器都可能down机不可服务     2)任意集群都可能处理能力不足     3)最坏情况一定会发生     4)内网环境需要低延迟来提供你最佳用户体验 4、关键设计     1)分布式集群化         a、理论上无限处理能力         b、集群级别高可用     2)强数据安全         a、单机磁盘级别冗余         b、单组多队列级别冗余         c、多组消息队列冗余     3)海量数据堆积         a、推模式:订阅者逻辑简单         b、拉模式:关注吞吐量,快         c、推拉结合:队列通知消费者,消费者去拉取(两次交互)         d、阿里采用长连接和轮询:轮询去拉,有则拉取,无则保持长连接等待,直到有消息     4)毫秒级投递延迟 5、关键概念     1)Topic:第一级消息类型,主标题     2)Tug:第二级消息类型,分标题     3)发送组:生产者所在集群     4)订阅组:消费者所在集群     5)RocketMQ不是一对一,也不是一对多,是随机一对一     6)网络三种状态:成功、失败、没响应 6、消息乱序问题:Message服务器不处理,恰好不需要解决     1)发送时对消息进行编号     2)一组消息只有唯一一个订阅者处理(sharding)     3)一组消息的数量(即“锁的颗粒度”)越小越好 7、消息重复问题     1)重复原因:网络不可达     2)幂等:某个操作无论重复多少次,结果都一样(不需要解决,性能极高)     3)非幂等,去重         a、保证有个唯一ID标记每一条消息;         b、保证消息处理成功与去重表日志同时出现     4)去重代价:额外的tps和qps 8、事务的分布式优化     1)事务1-->MQ Server-->事务2     2)同时成功,同时失败:         a、发消息;         b、执行事务1;         c、确认消息发送;         d、投递消息到消费者     3)处理超时问题(重复):事务2增加消息确认表(去重表)     4)消息失败(事务2失败):记录后人工处理(小概率事件)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值