package com.goafanti.common.utils;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.List;
import java.util.Set;
/**
 * redis辅助类
 * @author
 *
 */
@Component
public class RedisUtil {
	@Value(value = "${jedis.host}")
	private  String host;
	@Value(value = "${jedis.password}")
	private  String pwd;
	@Autowired
	private  JedisPool pool;//创建代理对象


	public static String SHIRO_SESSION="SHIRO_SESSION:";

//	 /**
//     * 初始化Redis连接池
//     */
//    public RedisUtil() {
//    	if (pool==null) {
//    		try {
//    			JedisPoolConfig config = new JedisPoolConfig();
//    			config.setBlockWhenExhausted(false);
//    			config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//    			config.setJmxEnabled(true);
//    			config.setJmxNamePrefix("pool");
//    			config.setLifo(true);
//    			config.setMaxIdle(8);
//    			config.setMaxTotal(8);
//    			config.setMaxWaitMillis(-1);
//    			config.setMinEvictableIdleTimeMillis(1800000L);
//    			config.setMinIdle(0);
//    			config.setNumTestsPerEvictionRun(3);
//    			config.setSoftMinEvictableIdleTimeMillis(1800000L);
//    			config.setTestOnBorrow(false);
//    			config.setTestWhileIdle(false);
//    			config.setTimeBetweenEvictionRunsMillis(-1);
//    			pool = new JedisPool(config, host, 6379, 10000, pwd);
//    		} catch (Exception e) {
//    			e.printStackTrace();
//    		}
//		}
//    }



	public boolean presence(String key){
		Jedis jedis = pool.getResource();
		boolean bool=true;
		try {
			bool =jedis.exists(key);//进行判断
		}catch(Exception e){
			e.printStackTrace();//输出错误信息
		}finally {
			jedis.close();//释放资源
		}
		return bool;
	}
	/**
	 * 将缓存中数据进行反序列化
	 * @param key
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T>List<T> getObject(String key,Class<T> clazz){
		Jedis jedis = pool.getResource();
		ByteArrayInputStream is=null;
		ObjectInputStream ois=null;
		try {
			//将缓存中数据存入byte数组中
			byte[] b = jedis.get(key.getBytes());
			is= new ByteArrayInputStream(b);
			ois = new ObjectInputStream(is);
			return(List<T>)ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			jedis.close();
		}
		return null;
	}
	/**
	 * 将对象进行序列化存入redis中
	 * @param object
	 * @param key
	 */
	public void saveObject(Object object,String key){
		Jedis jedis=pool.getResource();
		ByteArrayOutputStream os=null;
		ObjectOutputStream oos=null;
		try {
			os=new ByteArrayOutputStream();
			oos =new ObjectOutputStream(os);
			byte[] b=os.toByteArray();
			JSON.toJSONString(b);
			jedis.set(key.getBytes(), b);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
				oos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			jedis.close();
		}
	}
	// 把List集合对象转换成json格式保存到指定的键中
	public void saveJsonArray(Object object, String key) {
		Jedis jedis = pool.getResource();
		try {
			// 格式化成Json字符串
			String array = JSON.toJSONString(object);
			jedis.set(key, array.toString()); // 存入缓存
		} finally {
			jedis.close();
		}
	}

		public void setString(String key, String value) {
			Jedis jedis = pool.getResource();
			try {
				jedis.set(key,value); // 存入缓存
			} finally {
				jedis.close();
			}
		}

		public Set<String> keys(String key){
			Jedis jedis = pool.getResource();
			try {
				return  jedis.keys(key);
			} finally {
				jedis.close();
			}
		}

		public void deleteString(String key) {
			Jedis jedis = pool.getResource();
			try {
				jedis.del(key);
			} finally {
				jedis.close();
			}
		}


	public void deleteAid(String id) {
		Jedis jedis = pool.getResource();
		try {
			Set<String> set=jedis.keys(SHIRO_SESSION+id);
			for (String s : set) {
				deleteString(s);
				LoggerUtils.debug(this.getClass(),"清除缓存{%s,aid=%s}",s,id);
			}
		} finally {
			jedis.close();
		}
	}

		public String getString(String key) {
			Jedis jedis = pool.getResource();
			String str=new String();
			try {
				str=jedis.get(key);
			} finally {
				jedis.close();
			}
			return str;
		}

	// 通过键取出Json字符串并转换成 <T>这个T所指定的类型
	public  <T> T getJsonArray(String key, Class<T> clazz) {
		Jedis jedis = pool.getResource();
		try {
			String str = jedis.get(key);
			// 把字符串转换回集合对象 clazz是指定的类型
			return JSON.parseObject(str, clazz);
		} finally {
			jedis.close();
		}
	}

}


