Java利用Redis作缓存

有两种方案: 1.将对象转成JSON存入Redis;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);

    读取code

    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);

    读取get

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

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

相关文章
相关标签/搜索