自定义超实用Redis工具类(满足对象,list,map等类型)

自定义超实用Redis工具类(满足对象,list,map等类型)

该工具类,可以存储对象、list,map等各种数据类型到Redis中,大大有效提高开发效率。

1.添加maven依赖

    
    
        org.objenesis
        objenesis
        ${objenesis.version}
    
    
    
        com.dyuproject.protostuff
        protostuff-core
        ${dyuproject.version}
    
    
        com.dyuproject.protostuff
        protostuff-runtime
        ${dyuproject.version}
    

注:采用序列化工具进行解析。版本如下:

    1.1.3
    2.6

2.序列化工具类

/**
 * 序列化工具类
 * @Author: CatalpaFlat
 * @Descrition:
 * @Date: Create in 15:04 2017/11/11
 * @Modified BY:
 */
public class ProtoStuffSerializerUtil {
    public static  byte[] serialize(T obj) {
        if (obj == null) {
            throw new RuntimeException("序列化对象(" + obj + ")!");
        }
        @SuppressWarnings("unchecked")
        Schema schema = (Schema) RuntimeSchema.getSchema(obj.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
        } finally {
            buffer.clear();
        }
        return protostuff;
    }
    public static  T deserialize(byte[] paramArrayOfByte, Class targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }
        T instance = null;
        try {
            // T message = objenesis.newInstance(cls);
            instance = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e);
        }
        Schema schema = RuntimeSchema.getSchema(targetClass);
        ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
        return instance;
    }
    public static  byte[] serializeList(List objList) {
        if (objList == null || objList.isEmpty()) {
            throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
        }
        @SuppressWarnings("unchecked")
        Schema schema = (Schema) RuntimeSchema.getSchema(objList.get(0).getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
            protostuff = bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
        } finally {
            buffer.clear();
            try {
                if(bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return protostuff;
    }
    public static  List deserializeList(byte[] paramArrayOfByte, Class targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }

        Schema schema = RuntimeSchema.getSchema(targetClass);
        List result = null;
        try {
            result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
        } catch (IOException e) {
            throw new RuntimeException("反序列化对象列表发生异常!",e);
        }
        return result;
    }
    public static class Person{
        int id;
        String name;

        public Person(){

        }

        public Person(int id, String name){
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }
        public String getName() {
            return name;
        }

    }
}

3.配置redisConfig类进行存储

/**
 * redis配置类
 * @Author: CatalpaFlat
 * @Descrition:
 * @Date: Create in 15:04 2017/11/11
 * @Modified BY:
 */
@Component
public class RedisConfig {

    public final static String CAHCENAME = "CatalpaFlat";// 缓存名
    public final static int CAHCETIME = 60;// 默认缓存时间 60S
    public final static int CAHCEHOUR = 60 * 60;// 默认缓存时间 1hr
    public final static int CAHCEDAY = 60 * 60 * 24;// 默认缓存时间 1Day
    public final static int CAHCEWEEK = 60 * 60 * 24 * 7;// 默认缓存时间 1week
    public final static int CAHCEMONTH = 60 * 60 * 24 * 7 * 30;// 默认缓存时间 1month
    public final static int CAHCEYEAR = 60 * 60 * 24 * 7 * 30 * 12;// 默认缓存时间 1年
    @Autowired
    private RedisTemplate redisTemplate;

    public  boolean putCache(String key, T obj) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
        boolean result = redisTemplate.execute((RedisCallback) connection -> connection.setNX(bkey, bvalue));
        return result;
    }
    public  void putCacheWithExpireTime(String key, T obj, final long expireTime) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
        redisTemplate.execute((RedisCallback) connection -> {
            connection.setEx(bkey, expireTime, bvalue);
            return true;
        });
    }
    public  boolean putListCache(String key, List objList) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
        boolean result = redisTemplate.execute((RedisCallback) connection -> connection.setNX(bkey, bvalue));
        return result;
    }
    public  boolean putListCacheWithExpireTime(String key, List objList, final long expireTime) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
        boolean result = redisTemplate.execute((RedisCallback) connection -> {
            connection.setEx(bkey, expireTime, bvalue);
            return true;
        });
        return result;
    }
    public  T getCache(final String key, Class targetClass) {
        byte[] result = redisTemplate.execute(new RedisCallback() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.get(key.getBytes());
            }
        });
        if (result == null) {
            return null;
        }
        return ProtoStuffSerializerUtil.deserialize(result, targetClass);
    }
    public  List getListCache(final String key, Class targetClass) {
        byte[] result = redisTemplate.execute(new RedisCallback() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.get(key.getBytes());
            }
        });
        if (result == null) {
            return null;
        }
        return ProtoStuffSerializerUtil.deserializeList(result, targetClass);
    }
    /**
     * 精确删除key
     *
     * @param key
     */
    public void deleteCache(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 模糊删除key
     *
     * @param pattern
     */
    public void deleteCacheWithPattern(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 清空所有缓存
     */
    public void clearCache() {
        deleteCacheWithPattern(RedisConfig.CAHCENAME + "|*");
    }
}

4.测试序列化工具类

注:基于这篇文章
http://blog.csdn.net/DuShiWoDeCuo/article/details/78506579
/**
* @Author: CatalpaFlat
* @Descrition:
* @Date: Create in 10:08 2017/11/8
* @Modified BY:
/
@RunWith(SpringRunner.class)
@ContextConfiguration({"classpath:spring/
.xml"})
public class TestRedis {

    @Resource
    private RedisConfig redisConfig;
    @Autowired(required=true)
    private RedisKeyUtil redisKeyUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger log  = Logger.getLogger(TestRedis.class.getName());

    @Test
    public void test(){
//        redisTemplate.opsForValue().set("chen", "陈梓平");
//        log.info("value:"+redisTemplate.opsForValue().get("chen"));
        String key = redisKeyUtil.getSystemRedisKeyDistribution("Test", this.getClass().getName(), "test");
        log.info("cache-key:"+key);
        redisConfig.putCache(key,"测试链接");
        String cache = redisConfig.getCache(key, String.class);
        log.info("cache-value:"+cache);
    }
}
自定义超实用Redis工具类(满足对象,list,map等类型)_第1张图片
image

你可能感兴趣的:(自定义超实用Redis工具类(满足对象,list,map等类型))