1、將對象序列化成字節數組,存入String中
/** * 將對象緩存到redis的string結構數據中 * @throws Exception * */ @Test public void testObjectCache() throws Exception{ ProductInfo p = new ProductInfo(); p.setName("中華牙膏"); p.setDescription("美白防蛀"); p.setCatelog("日用品"); p.setPrice(10.8); //將對象序列化成字節數組 ByteArrayOutputStream ba = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ba); //用對象序列化流來將p對象序列化,然后把序列化之后的二進制數據寫到ba流中 oos.writeObject(p); //將ba流轉成byte數組 byte[] pBytes = ba.toByteArray(); //將對象序列化之后的byte數組存到redis的string結構數據中 jedis.set("product:01".getBytes(), pBytes); //根據key從redis中取出對象的byte數據 byte[] pBytesResp = jedis.get("product:01".getBytes()); //將byte數據反序列出對象 ByteArrayInputStream bi = new ByteArrayInputStream(pBytesResp); ObjectInputStream oi = new ObjectInputStream(bi); //從對象讀取流中讀取出p對象 ProductInfo pResp = (ProductInfo) oi.readObject(); System.out.println(pResp); }
2、將對象轉成json字符串緩存到redis的string結構數據中
/** * 將對象轉成json字符串緩存到redis的string結構數據中 */ @Test public void testObjectToJsonCache(){ ProductInfo p = new ProductInfo(); p.setName("兩面針"); p.setDescription("防蛀專用"); p.setCatelog("日用品"); p.setPrice(10.9); //利用gson將對象轉成json串 Gson gson = new Gson(); String pJson = gson.toJson(p); //將json串存入redis jedis.set("prodcut:02", pJson); //從redis中取出對象的json串 String pJsonResp = jedis.get("prodcut:02"); //將返回的json解析成對象 ProductInfo pResponse = gson.fromJson(pJsonResp, ProductInfo.class); //顯示對象的屬性 System.out.println(pResponse); }
3、ProductInfo對象代碼
import java.io.Serializable; public class ProductInfo implements Serializable{ private static final long serialVersionUID = 3002512957989050750L; private String name; private String description; private double price; private String catelog; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getCatelog() { return catelog; } public void setCatelog(String catelog) { this.catelog = catelog; } @Override public String toString() { return name+" "+description + " "+ catelog+ " " + price; } }