package com.elab.mq.rocketmq;

import com.aliyun.openservices.ons.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

public class ConsumerTest {
    private static Logger logger = LoggerFactory.getLogger(ConsumerTest.class);

    public static void main(String[] args) {
        Properties properties = new Properties();
        // 您在控制台创建的 Group ID
//        properties.put(PropertyKeyConst., "GID-producer1");
        // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey, "LTAImNZed054h0YV");
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, "8hmhlhiQ2ikmVeLKujwMNWsktFpSzm");
        // 设置 TCP 接入域名，进入控制台的实例管理页面的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                "http://MQ_INST_1819241776271348_Bak3xjk0.mq-internet-access.mq-internet.aliyuncs.com:80");
        // 集群订阅方式 (默认)
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        // 广播订阅方式
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe("test", "mq_test", new MessageListener() { //订阅多个 Tag
            private int count = 0;

            public Action consume(Message message, ConsumeContext context) {
                count++;
                if (count > 3) {
                    logger.info("消息被确认了..." + message.getKey() + "\t" + message.getMsgID());
                    count = 0;
                    return Action.CommitMessage;
                } else {
                    logger.info("------消息不想被确认-------" + count + "\t" + message.getKey() + "\t" + message.getMsgID());
                    return Action.ReconsumeLater;
                }
            }
        });
        //订阅另外一个 Topic
//        consumer.subscribe("TopicTestMQ-Other", "*", new MessageListener() { //订阅全部 Tag
//            public Action consume(Message message, ConsumeContext context) {
//                System.out.println("Receive: " + message);
//                return Action.CommitMessage;
//            }
//        });
        consumer.start();
        logger.info("Consumer Started");
    }
}