package com.gyee.frame.common.conf.redis;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;

/**
 *  Author: Wang_jw
 *  缓存写入类
 *  缓存获取类
 */
@Configuration
public class CacheConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *@author:Wang Jiawen
     *
     *@description:  在创建的时候就自动的将缓存写入
     *
     *@param:[bool]
     *
     *@return:void
     *
     *@createTime:2020/3/9
     *
     */
    public void cacheManager(Boolean bool) {

        if (bool) {
           // this.putinredis("usePowerstationidGetWindpowerstation", this.serialize(usePowerstationidGetWindpowerstation));
        }
    }




    /**
     * 向redis中存入数据 不提供转换 请自己用Json进行装换
     * param key 建 ，str json字符串
      */
    public void putinredis(String key,Object str){
        redisTemplate.delete(key);
        redisTemplate.opsForValue().set(key,str);
    }

    /**
     * 从redis中取数据 提供JsonObject转换但是返回Object类型,请自己转换类型
     * param key 建
     */
    public String getFromredisToString(String key){
        String str = (String) redisTemplate.opsForValue().get(key);
        return str;
    }





    public byte[] serialize(Object obj){
        if(obj==null){
            throw new NullPointerException("can not read obj");
        }

        byte[] rv=null;
        ByteArrayOutputStream bao=null;
        ObjectOutputStream oto=null;
        try{
            bao=new ByteArrayOutputStream();
            oto=new ObjectOutputStream(bao);
            oto.writeObject(obj);
            rv=bao.toByteArray();

        }catch(Exception e){
             // //System.out.println(e.getMessage());
              e.printStackTrace();
        }
        return rv;
    }

    public Object deserialize(byte[] byt){
        if(byt==null){
            throw new NullPointerException();
        }
        ByteArrayInputStream bai=null;
        ObjectInputStream ois=null;
        Object obj=null;
        try{
            bai=new ByteArrayInputStream(byt);
            ois=new ObjectInputStream(bai);
            obj=ois.readObject();
        }catch(Exception e){

        }
        return (Object) obj;
    }
}
