package com.elab.mq.rocket.msg;

import com.elab.mq.rocket.msg.entity.RmqConsumerEntity;
import com.elab.mq.rocket.utils.MsgConstants;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 内存消息存储
 *
 * @author ： liukx
 * @time ： 2019/7/22 - 14:32
 */
public class MemoryDataStore implements ConsumerDataStore {
    private Map<String, RmqConsumerEntity> cacheMap = Maps.newConcurrentMap();
    private LoadingCache<String, RmqConsumerEntity> cacheBuilder = CacheBuilder.newBuilder().expireAfterAccess(5L,
            TimeUnit.SECONDS)
            .build(new CacheLoader<String, RmqConsumerEntity>() {
                @Override
                public RmqConsumerEntity load(String key) throws Exception {
                    return cacheMap.get(key);
                }
            });

    @Override
    public boolean add(RmqConsumerEntity keyModel) throws Exception{
        Integer consumerStatus = keyModel.getConsumerStatus();
        String key = getKey(keyModel.getConsuemrGroup(), keyModel.getMsgKey());
        // 除了
        if (MsgConstants.MSG_OK == consumerStatus) {
            cacheBuilder.put(key, keyModel);
            return true;
        }
        return false;
    }

    /**
     * 存储的key
     *
     * @param group
     * @param key
     * @return
     */
    private String getKey(String group, String key) throws Exception{
        return group + "_" + key;
    }

    @Override
    public RmqConsumerEntity getMsgKey(String group, String key) throws Exception{
        return cacheMap.get(getKey(group, key));
    }

    @Override
    public boolean update(RmqConsumerEntity entity) throws Exception{
        return false;
    }

    @Override
    public RmqConsumerEntity getMsgId(String group, String msgId) throws Exception{
        return null;
    }
}
