有兩種方案: 1.將對象轉成JSON存入Redis;redis
2.將對象序列化存入Redis數據庫
將對象轉成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;
將對象序列化存入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