Java利用Redis做缓存

有两种方案: 1.将对象转成JSON存入Redis;

2.将对象序列化存入Redis

  1. 将对象转成JSON存入Redis

    写入

     jedis = new Jedis("localhost");
     //将obj转成JSON字符串信息
     Gson gson = new Gson();
     String value = gson.toJson(obj);
     //将信息写入redis
     jedis.set(key, value);
    

    读取

     Jedis jedis = new Jedis("localhost");
     String value = jedis.get(key);
     Object obj = null;
     if(value != null){
     	//将JSON串转成Object
     	Gson gson = new Gson();
     	obj = gson.fromJson(value, type);
     }
     return obj;
    
  2. 将对象序列化存入Redis

    写入

     //序列化
     baos = new ByteArrayOutputStream();
     oos = new ObjectOutputStream(baos);
     oos.writeObject(object);//将对象序列化
     byte[] bytes = baos.toByteArray();
     //将序列化字节数组写入redis
     jedis.set("person:101".getBytes(),bytes);
    

    读取

     byte[] person = jedis.get(("person:101").getBytes())
     bais = new ByteArrayInputStream(person);
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
    

    注意:增删改操作后,缓存和数据库一致性。

猜你喜欢

转载自my.oschina.net/u/3577079/blog/1543072