This tool class can store objects, lists, maps and other data types into Redis, greatly improving the development efficiency.

1. Add maven dependencies

<! Objenesis </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>Copy the code

Note: The serialization tool was used for parsing. The version is as follows:

< dyuproject version > 1.1.3 < / dyuproject version > < objenesis. Version > 2.6 < / objenesis version >Copy the code

2. Serialize utility classes

** ** Serialization tools * @author: CatalpaFlat * @descrition: * @date: CreateinPublic class ProtoStuffSerializerUtil {public static <T> byte[] serialize(T obj) {if (obj == null) {
            throw new RuntimeException("Serialize objects (" + 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("Serialize (" + obj.getClass() + Object (" ") + obj + ") An exception has occurred!, 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("Deserialization object exception,byte sequence is empty!");
        }
        T instance = null;
        try {
            // T message = objenesis.newInstance(cls);
            instance = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(Failed to create object by type during deserialization!, 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("List of serialized objects (" + objList + ") parameter abnormal!");
        }
        @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("List of serialized objects (" + objList + ") An exception has occurred!, 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("Deserialization object exception,byte sequence is empty!");
        }

        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        List<T> result = null;
        try {
            result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
        } catch (IOException e) {
            throw new RuntimeException("Deserialization object list exception!",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() {
            returnname; }}}Copy the code

3. Configure the redisConfig class for storage

/** * redis * @author: CatalpaFlat * @descrition: * @date: Createin15: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; Public final static int CAHCEDAY = 60 * 60 * 24; Public final static int CAHCEWEEK = 60 * 60 * 24 * 7; Week public final static int CAHCEMONTH = 60 * 60 * 24 * 7 * 30; Month public final static int CAHCEYEAR = 60 * 60 * 24 * 7 * 30 * 12; month public final static int CAHCEYEAR = 60 * 60 * 24 * 7 * 30 * 12; @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));returnresult; } 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 {
                returnconnection.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 {
                returnconnection.get(key.getBytes()); }});if (result == null) {
            return null;
        }
        returnProtoStuffSerializerUtil.deserializeList(result, targetClass); } /** * @param key */ public void deleteCache(String key) {redistemplate.delete (key); } /** * public void deleteCacheWithPattern(String pattern) {Set<String> keys = redisTemplate.keys(pattern); redisTemplate.delete(keys); } /** * clear all caches */ public voidclearCache() {
        deleteCacheWithPattern(RedisConfig.CAHCENAME + "| *"); }}Copy the code

4. Test the serialization utility class

Note: based on the article blog.csdn.net/DuShiWoDeCu…

/**
 * @Author: CatalpaFlat
 * @Descrition:
 * @Date: Create in10:08 2017/11/8 * @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"."Chen Ping");
//        log.info("value:"+redisTemplate.opsForValue().get("chen"));
        String key = redisKeyUtil.getSystemRedisKeyDistribution("Test", this.getClass().getName(), "test");
        log.info("cache-key:"+key);
        redisConfig.putCache(key,"Test link");
        String cache = redisConfig.getCache(key, String.class);
        log.info("cache-value:"+cache); }}Copy the code