Redis_简单的redis 缓存

在pom.xml加入如下内容:  //高速序列化 存储对象 速度是java 实现io 序列化的10倍左右 存储较大的对象时 内置缓存 java

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>

</dependency>

//redis 客户端 jedis 也可使用别的 推荐redis

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>

</dependency>


 

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>

 

//业务层获取jedis 链接池数据库

public RedisDao(String ip,int port) {
        // TODO Auto-generated constructor stub
        
        jedisPool= new JedisPool(ip,port);
    }


//redis 就是key value 数据库 传入key值获取你所要的对象缓存

//entityclass就是你要序列化的类code

//经过key值获取redis中的缓存对象xml

public T test(String key){
        RuntimeSchema<T> schema = RuntimeSchema.createFrom(entityclass);
        Jedis jedis = jedisPool.getResource();//获取jedis 对象
                
        byte [] bytes= jedis.get(key.getBytes());
        T a =schema.newMessage();        
        if(bytes!=null){    
            ProtobufIOUtil.mergeFrom(bytes, a, schema) ;
            jedis.close();
            return a;
        }
        return null;
        
    }

//若是该key值中没有对应的对象对象

//访问数据 返回的对象存入redis中ip

  //LinkedBuffer redis 中缓冲的对象get

 public void putT(T t){
        RuntimeSchema<T> schema = RuntimeSchema.createFrom(entityclass);
        //OBJECT -->序列化-->存入redis
        Jedis jedis = jedisPool.getResource();
        //缓冲对象
        byte [] bytes=ProtobufIOUtil.toByteArray(t, schema,   LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
        int timeout = 60 * 60;//缓存的时长 秒为单位
        String key = null;
        jedis.setex(key.getBytes(), timeout, bytes);    
    
    }
相关文章
相关标签/搜索