jvm-序列化优化以及redis中的使用。

公西英叡
2023-12-01

自定义持久化
jvm-Serialization jvm优化。

优点,序列化时间短,转换后空间小。压缩空间大概为jvm自带Serialization 的1/5-1/10 压缩速度提高几倍。提高序列化性能。

 

maven依赖

<!--prostuff序列化依赖 -->
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-core</artifactId>
    <version>1.0.8</version>
</dependency>
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-runtime</artifactId>
    <version>1.0.8</version>
</dependency>

实现代码

//引用路径
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


public class prostuffTest {

    private final JedisPool jedisPool;
    private RuntimeSchema<UserPo> userSchema = RuntimeSchema.createFrom(UserPo.class);

    //获取对象
    public UserPo getUser(long userId) {
        try {
        
            //获取redis 客户端
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "userId:" + userId;
                //获取缓存对象
                byte[] bytes = jedis.get(key.getBytes());
                if (bytes != null) {
                
                    //通过schema创建空对象
                    UserPo userPo = userSchema.newMessage();
                    
                    //反序列化到此对象
                    ProtostuffIOUtil.mergeFrom(bytes, userPo, userSchema);

                    //返回反序列化后的对象
                    return userPo;
                }
            } finally {
            
                //关闭redis连接
                jedis.close();
            }
        } catch (Exception e) {

        }
        return null;
    }
    
    
    
    //存储对象
    public String setUser(UserPo userPo) {
    
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "userId:" + userPo.getUserId();
                
                //对象序列化为字节数组 对象,schema,压缩缓存默认大小
                byte[] bytes = ProtostuffIOUtil.toByteArray(userPo, userSchema,
                        LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
                        
                // 超时缓存
                int timeout = 60 * 60;// 1小时
                String result = jedis.setex(key.getBytes(), timeout, bytes);

                return result;
            } finally {
                jedis.close();
            }
        } catch (Exception e) {
            //
        }

        return null;
    }
}

 

序列化性能测试数据对照:https://github.com/eishay/jvm-serializers/wiki

 

转载于:https://www.cnblogs.com/yanxioayu/p/10982486.html

 类似资料: