package com.hdkj.lt.core.config;

import com.hdkj.lt.utils.cache.RedisUtil;
import org.apache.ibatis.cache.Cache;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yulei
 * @date 2021-06-01
 */
public class MybatisRedisCache implements Cache {

    private String id = null;

    private static RedisUtil redisUtil = null;

    public static final String CACHE_KEY_PREFIX = "MSQL:BI_MYBATIS_";

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public MybatisRedisCache(final String id) {
        this.id = id;
    }

    public static void setRedisUtil(RedisUtil redisUtil) {
        MybatisRedisCache.redisUtil = redisUtil;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object val) {
        redisUtil.set(CACHE_KEY_PREFIX + key.toString(), val, 3600 * 48);
    }

    @Override
    public Object getObject(Object key) {
        return redisUtil.get(CACHE_KEY_PREFIX + key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        return redisUtil.expire(CACHE_KEY_PREFIX + key.toString(), 0);
    }

    @Override
    public void clear() {
        // 清除...
    }

    @Override
    public int getSize() {
        return redisUtil.keys(CACHE_KEY_PREFIX + "*").size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

}
