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

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

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

1.添加maven依赖

    <!--序列化工具-->
    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>${objenesis.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.dyuproject.protostuff/protostuff-core -->
    <dependency>
        <groupId>com.dyuproject.protostuff</groupId>
        <artifactId>protostuff-core</artifactId>
        <version>${dyuproject.version}</version>
    </dependency>
    <dependency>
        <groupId>com.dyuproject.protostuff</groupId>
        <artifactId>protostuff-runtime</artifactId>
        <version>${dyuproject.version}</version>
    </dependency>

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

    <dyuproject.version>1.1.3</dyuproject.version>
    <objenesis.version>2.6</objenesis.version>

2.序列化工具类

/**
 * 序列化工具类
 * @Author: CatalpaFlat
 * @Descrition:
 * @Date: Create in 15:04 2017/11/11
 * @Modified BY:
 */
public class ProtoStuffSerializerUtil {
    public static <T> byte[] serialize(T obj) {
        if (obj == null) {
            throw new RuntimeException("序列化对象(" + obj + ")!");
        }
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) 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> T deserialize(byte[] paramArrayOfByte, Class<T> 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<T> schema = RuntimeSchema.getSchema(targetClass);
        ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
        return instance;
    }
    public static <T> byte[] serializeList(List<T> objList) {
        if (objList == null || objList.isEmpty()) {
            throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
        }
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) 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 <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }

        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        List<T> 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<String, String> redisTemplate;

    public <T> boolean putCache(String key, T obj) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
        boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.setNX(bkey, bvalue));
        return result;
    }
    public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
        redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            connection.setEx(bkey, expireTime, bvalue);
            return true;
        });
    }
    public <T> boolean putListCache(String key, List<T> objList) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
        boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.setNX(bkey, bvalue));
        return result;
    }
    public <T> boolean putListCacheWithExpireTime(String key, List<T> objList, final long expireTime) {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
        boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            connection.setEx(bkey, expireTime, bvalue);
            return true;
        });
        return result;
    }
    public <T> T getCache(final String key, Class<T> targetClass) {
        byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.get(key.getBytes());
            }
        });
        if (result == null) {
            return null;
        }
        return ProtoStuffSerializerUtil.deserialize(result, targetClass);
    }
    public <T> List<T> getListCache(final String key, Class<T> targetClass) {
        byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
            @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<String> 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等类型)》 image

    原文作者:CatalpaFlat
    原文地址: https://www.jianshu.com/p/ecc4b9d78335
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞