美文网首页
Redis+protostuff序列化工具实现热点对象缓存

Redis+protostuff序列化工具实现热点对象缓存

作者: 神蛋_狄仁杰 | 来源:发表于2018-08-07 10:48 被阅读0次

    很多情况我们为了解决并发问题使用redis非关系型数据库保存数据,我们序列化保存热点数据的传输可以随时把对象持久化到数据库、文件等系统里,也方便我们反序列化获取对象,从而提高用户体验和系统性能

    1.利用maven管理项目,导入相关jar包

    
    <dependency>
    
      <groupId>redis.clients</groupId>
    
      <artifactId>jedis</artifactId>
    
      <version>2.9.0</version>
    
    </dependency>
    
    <dependency>
    
      <groupId>com.dyuproject.protostuff</groupId>
    
      <artifactId>protostuff-core</artifactId>
    
      <version>1.1.1</version>
    
    </dependency>
    
    <dependency>
    
      <groupId>com.dyuproject.protostuff</groupId>
    
      <artifactId>protostuff-runtime</artifactId>
    
      <version>1.1.1</version>
    
    </dependency>
    
    

    2.编写protostuff工具类,实现对象序列化和反序列化

    
    import com.dyuproject.protostuff.LinkedBuffer;
    
    import com.dyuproject.protostuff.ProtostuffIOUtil;
    
    import com.dyuproject.protostuff.Schema;
    
    import com.dyuproject.protostuff.runtime.RuntimeSchema;
    
    import lombok.extern.slf4j.Slf4j;
    
    /**
    
    * protostuff序列化工具
    
    *
    
    * @auth liubing
    
    * @date 2018-03-22
    
    */
    
    @Slf4j
    
    public class ProtostuffUtil {
    
        public ProtostuffUtil() {
    
        }
    
        /**
    
        * 对象序列化
    
        * @paramo 需要序列化对象
    
        * @param 序列化对象类型
    
        * @return
    
        */
    
        public static byte[] serializer(T o) {
    
            // 通过对象的类构建对应的schema
    
            Schema schema= RuntimeSchema.createFrom(o.getClass());
    
            // 将对象通过动态生成的schema转换成字节数组
    
            // LinkedBuffer用于缓存较大的对象
    
            return ProtostuffIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
    
        }
    
        /**
    
        * 对象反序列化
    
        * @parambytes 对象字节数组
    
        * @paramclazz Class对象
    
        * @param 反序列化对象
    
        * @return
    
        */
    
        public static T deserializer(byte[] bytes, Class clazz) {
    
            T obj= null;
    
            try {
    
                // 通过对象的类构建对应的schema;
    
                Schema schema= RuntimeSchema.createFrom(clazz);
    
                // 通过schema新建一个对象,这里需要转换一下
    
                obj= (T) schema.newMessage();
    
                // 数据反序列化
    
                ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
    
            } catch (Exception e) {
    
                log.error(e.getMessage(),e);
    
            }
    
            return obj;
    
        }
    
    }
    
    

    3.redis 数据库操作

    import lombok.extern.slf4j.Slf4j;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.stereotype.Repository;
    
    import redis.clients.jedis.Jedis;
    
    import redis.clients.jedis.JedisSentinelPool;
    
    /**
    
    * 思路:
    
    * 1.查找数据时,首先向Redis缓存中查找.
    
    * 2.如果找不到,就转向数据库中查找.
    
    * 2.1将查找到的数据放进Redis缓存中
    
    * 3.返回查找到的对象
    
    *
    
    * Created by liubing on 2018/3/21.
    
    */
    
    @Slf4j
    
    @Repository
    
    public class RedisCacheDao {
    
        @Autowired
    
        private JedisSentinelPool jedisSentinelPool;
    
        /**
    
        * 从redis中查找数据
    
        * @paramsecKillId
    
        * @return查询到的对象
    
        */
    
        public SecKill getSecKill(Long secKillId){
    
                // 逻辑
    
                Jedis jedis= jedisSentinelPool.getResource();
    
                try {
    
                    String key= "secKill_" + secKillId;
    
                    // 从Jedis中获取序列化的字节数组
    
                    byte[] bytes= jedis.get(key.getBytes());
    
                    if (bytes!= null) {
    
                        // 将字节数组再反序列化SecKill
    
                        SecKill secKill= ProtostuffUtil.deserializer(bytes, SecKill.class);
    
                        // secKill被反序列化
    
                        return secKill;
    
                    }
    
                }finally {
    
                    jedis.close();
    
                }
    
            return null;
    
        }
    
        /**
    
        * 将对象放入redis中
    
        * @paramsecKill
    
        * @return如果在键中设置了值则返回OK。如果值未设置则返回null
    
        */
    
        public String putSecKill(SecKill secKill){
    
            // 逻辑
    
            try {
    
                Jedis jedis= jedisSentinelPool.getResource();
    
                try {
    
                    String key= "secKill_" + secKill.getSecKillId();
    
                    // 将对象转换成字节数组
    
                    byte[] bytes= ProtostuffUtil.serializer(secKill);
    
                    // 超时缓存
    
                    // Redis存储数据可以是永久的或是时限的
    
                    // 对于数据库缓存来说,一般使用超时机制来保证数据缓存与数据库数据的完整性
    
                    int timeout= 60*60;
    
                    String result= jedis.setex(key.getBytes(),timeout,bytes);
    
                    return  result;
    
                } finally {
    
                    jedis.close();
    
                }
    
            } catch (Exception e){
    
                log.error(e.getMessage(),e);
    
            }
    
            return null;
    
        }
    
    }
    
    

    使用哨兵机制redis服务,配置文件如下:

    
    import lombok.extern.slf4j.Slf4j;
    
    import org.springframework.beans.factory.annotation.Value;
    
    import org.springframework.context.annotation.Bean;
    
    import org.springframework.context.annotation.Configuration;
    
    import redis.clients.jedis.HostAndPort;
    
    import redis.clients.jedis.JedisPoolConfig;
    
    import redis.clients.jedis.JedisSentinelPool;
    
    import java.util.HashSet;
    
    import java.util.Set;
    
    /**
    
    * @auth liubing
    
    * @date 2018-03-22
    
    */
    
    @Configuration
    
    @Slf4j
    
    public class RedisSourceConfig {
    
        @Value("${redis.maxActive}")
    
        private String maxActive;
    
        @Value("${redis.maxIdle}")
    
        private String maxIdle;
    
        @Value("${redis.minIdle}")
    
        private String minIdle;
    
        @Value("${redis.sentinel.host}")
    
        private String sentinelHost;
    
        @Value("${redis.sentinel.port}")
    
        private String sentinelPort;
    
        @Value("${redis.cluster.clusterName}")
    
        private String masterName;
    
        @Bean
    
        public JedisPoolConfig jedisPoolConfig(){
    
            JedisPoolConfig jedisPoolConfig= new JedisPoolConfig();
    
            jedisPoolConfig.setMaxTotal(Integer.parseInt(maxActive));
    
            jedisPoolConfig.setMaxIdle(Integer.parseInt(maxIdle));
    
            jedisPoolConfig.setMinIdle(Integer.parseInt(minIdle));
    
            jedisPoolConfig.setTestOnBorrow(false);
    
            jedisPoolConfig.setTestOnReturn(false);
    
            jedisPoolConfig.setTestWhileIdle(true);
    
            return jedisPoolConfig;
    
        }
    
        @Bean
    
        public JedisSentinelPool jedisSentinelPool(JedisPoolConfig jedisPoolConfig){
    
            Set sentinels= new HashSet();
    
            HostAndPort sentinelHostAndPort= new HostAndPort(sentinelHost, Integer.parseInt(sentinelPort));
    
            sentinels.add(sentinelHostAndPort.toString());
    
            JedisSentinelPool jedisSentinelPool= new JedisSentinelPool(masterName, sentinels, jedisPoolConfig);
    
            return jedisSentinelPool;
    
        }
    
    }
    
    

    总结:这个方法适合存储对象,因为重点是redis保存数据时序列化与获取数据反序列化。

    相关文章

      网友评论

          本文标题:Redis+protostuff序列化工具实现热点对象缓存

          本文链接:https://www.haomeiwen.com/subject/wjsovftx.html