自定义对象存入Redis

package com.cms.common;

import com.alibaba.fastjson.JSON;
import com.qiyi.tvguo.cms.common.utils.ObjectSerializeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * redis client
 */
@Component
@Slf4j
public class RedisClient {

    private static  JedisPool pool;

    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.password}")
    private String password;

    private  final int timeout=5000;
    private  final int database=0;
    private  final int maxConnection=500;
    private  final int maxIdle=50;
    private  final int minIdle=20;

    @PostConstruct
    public   void  init()
    {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxConnection);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);
        pool = new JedisPool(config, host,port,timeout, password, database);
        log.info("------jedis pool init------");
    }

    /**
     * 获取jedis
     * @return
     */
    public Jedis getJedis()
    {
        return pool.getResource();
    }


    @PreDestroy
    public  void  destroy()
    {
        if(pool==null)
        {
            return;
        }

        pool.destroy();
        log.info("-----jedis pool destroy-----");
    }


    /**
     * 复杂对象存入redis
     * @param key
     * @param v
     * @param expireSeconds
     * @param <T>
     * @return
     */
    public <T> Boolean setExByte(String key,T v,int expireSeconds)
    {
        Jedis jedis=null;
        try
        {
            jedis= getJedis();
            jedis.setex(key.getBytes(),expireSeconds,ObjectSerializeUtil.serialize(v));
            return true;

        }catch (Exception ex)
        {
            log.error("复杂对象存入redis异常:{}",ex);

        }finally {
            if(jedis!=null)
            {
                jedis.close();
            }
        }

        return  false;
    }


    /**
     * 获取Value 为byte[]的复杂对象
     * @param key
     * @param <T>
     * @return
     */
    public <T> T getByteObject(String key)
    {
        Jedis jedis=null;
        try
        {
            jedis= getJedis();
            byte[] bytes= jedis.get(key.getBytes());
            return  (T)ObjectSerializeUtil.unserizlize(bytes);

        }catch (Exception ex)
        {
            log.error("redis获取复杂对象异常:{}",ex);

        }finally {
            if(jedis!=null)
            {
                jedis.close();
            }
        }

        return  null;
    }


    /**
     * 对象以JSON存入redis
     * @param key
     * @param obj
     * @param expireSeconds
     * @param <T>
     * @return
     */
    public <T> Boolean setExJson(String key,T obj,int expireSeconds)
    {
        Jedis jedis=null;
        try
        {
            jedis= getJedis();
            jedis.setex(key,expireSeconds, JSON.toJSONString(obj));
            return true;

        }catch (Exception ex)
        {
            log.error("复杂对象存入redis异常:{}",ex);
        }finally {
            if(jedis!=null)
            {
                jedis.close();
            }
        }

        return  false;
    }


    /**
     * 获取Value 为Json的复杂对象
     * @param key
     * @param <T>
     * @return
     */
    public <T extends  Object> T getJsonObject(String key,Class<T> clazz)
    {
        Jedis jedis=null;
        try
        {
            jedis= getJedis();
            String jsonString= jedis.get(key);
          return JSON.parseObject(jsonString, clazz);

        }catch (RuntimeException ex)
        {
            log.error("redis获取Json复杂对象异常:{}",ex);

        } finally {
            if(jedis!=null)
            {
                jedis.close();
            }
        }

        return null;
    }



}

 

package com.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;


@Slf4j
public class ObjectSerializeUtil implements  Serializable {

    /**
     * 序列化对象
     * @param obj
     * @param <T> T 必须实现Serializable接口,
     *           T 中尽量加上 serialVersionUID (private static final long serialVersionUID)
     * @return
     */
    public static <T> byte [] serialize(T obj){
        ObjectOutputStream outputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        try {
            byteArrayOutputStream=new ByteArrayOutputStream();
            outputStream=new ObjectOutputStream(byteArrayOutputStream);
            outputStream.writeObject(obj);
            byte[] byteArray=byteArrayOutputStream.toByteArray();
            return byteArray;
        } catch (IOException e) {
           log.error("ObjectSerializeUtil-IOException:{}",e);
        }
        return null;
    }

    /**反序列化对象
     * @param byteArray
     * @param <T>T 必须实现Serializable接口,
     *      *           T 中尽量加上 serialVersionUID (private static final long serialVersionUID)
     * @return
     */
    public static <T> Object unserizlize(byte[] byteArray){
        ObjectInputStream inputStream;
        ByteArrayInputStream byteArrayInputStream;
        byteArrayInputStream=new ByteArrayInputStream(byteArray);
        try {
            inputStream=new ObjectInputStream(byteArrayInputStream);
            T obj=(T)inputStream.readObject();
            return obj;
        } catch (Exception e) {
            log.error("ObjectSerializeUtil-IOException:{}",e);
        }

        return null;
    }

}

 

posted @ 2018-07-20 13:00  kingNull  阅读(3219)  评论(0编辑  收藏  举报