package com.njcn.shiro.cache;



import com.njcn.pojo.commons.RedisDB;
import com.njcn.utils.SerializeUtil;
import com.njcn.utils.SpringContextUtil;
import com.njcn.utils.redis.JedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;


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

	final static JedisManager J = SpringContextUtil.getBean("jedisManager", JedisManager.class);

	private VCache() {}
	
	/**
	 * 简单的Get
	 * @param key 键
	 * @param requiredType 需求的类型
	 */
	public static <T> T get(String key , Class<T>...requiredType){
		Jedis jds = null;
		try {
			jds = J.getJedis();
			jds.select(RedisDB.USER_SESSION);
			byte[] skey = SerializeUtil.serialize(key);
			return SerializeUtil.deserialize(jds.get(skey),requiredType);
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            returnResource(jds);
        }
		return null;
	}
	/**
	 * 简单的set
	 */
	public static void set(Object key ,Object value){
		Jedis jds = null;
		try {
			jds = J.getJedis();
			jds.select(RedisDB.USER_SESSION);
			byte[] skey = SerializeUtil.serialize(key);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.set(skey, svalue);
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            returnResource(jds);
        }
	}

	/**
	 * 过期时间的
	 */
	public static void setex(Object key, Object value, int timer) {
		Jedis jds = null;
		try {
			jds = J.getJedis();
			jds.select(RedisDB.USER_SESSION);
			byte[] skey = SerializeUtil.serialize(key);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.setex(skey, timer, svalue);
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            returnResource(jds);
        }
		
	}

	/**
	 * 删除
	 */
	public static Long delByKey(String...dkey){
		Jedis jds = null;
		try {
			jds = J.getJedis();
			jds.select(0);
			byte[][] dx = new byte[dkey.length][];
			for (int i = 0; i < dkey.length; i++) {
				dx[i] = SerializeUtil.serialize(dkey[i]);
			}
			Long result = jds.del(dx);
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			returnResource(jds);
		}
		return new Long(0);
	}
	/**
	 * 判断是否存在
	 */
	public static boolean exists(String existskey){
		Jedis jds = null;
		try {
			jds = J.getJedis();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(existskey);
			return jds.exists(lkey);
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			returnResource(jds);
		}
		return false;
	}

	/**
	 * 释放
	 */
	public static void returnResource(Jedis jedis) {
        if (jedis == null)
            return;
         jedis.close();
	 }
}
