redis將物件序列化儲存
阿新 • • 發佈:2019-01-06
redis是一種nosql的語言,常用來作為快取,而且redis是一種高效能的儲存架構,是以key value方式儲存
這裡通過jedis來序列化物件來存入redis中
編寫序列化工具類,大家應該都不預設,序列化,就是流化,將其轉為位元組碼byte,然後我們一般是通過物件流來實現的
序列化的物件:package com.jedis.aisainfo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class SerializeUtil { /** * 序列化 * @param list * @return */ public static byte[] serialize(List<User> list){ //申明存放陣列 byte[] arr = null; //物件流,用於序列化物件 ObjectOutputStream os = null; //臨時輸入流 ByteArrayOutputStream bos=null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); os.writeObject(list); arr=bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); }finally{ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } return arr; } /** * 反序列化 * @param in * @return */ public static List<User> unserialize(byte[] in){ List<User> list = null; //臨時輸入流 ByteArrayInputStream bis = null; //讀取物件流 ObjectInputStream ois =null; try { list = new ArrayList<User>(); bis = new ByteArrayInputStream(in); ois = new ObjectInputStream(bis); list = (List<User>)ois.readObject(); } catch (Exception e) { e.printStackTrace(); }finally{ try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } }
測試類:package com.jedis.aisainfo; import java.io.Serializable; public class User implements Serializable{ private Integer id; private String username; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
private Jedis jedis=null; @Before public void init(){ jedis = new Jedis("localhost"); } @Test public void addObjectInfo(){ List<User> list = new ArrayList(); User user1 = new User(); user1.setAge(1); user1.setUsername("曾孟良"); user1.setId(1); User user2 = new User(); user2.setAge(1); user2.setUsername("陸燕"); user2.setId(1); list.add(user1); list.add(user2); jedis.set("user".getBytes(), SerializeUtil.serialize(list)); } @Test public void queryObjectInfo(){ byte[] users = jedis.get("user".getBytes()); List<User> list = SerializeUtil.unserialize(users); for(User user:list){ System.out.println(user.getUsername()); System.out.println(user.getId()); } }
先執行addObjectInfo,然後queryObjectInfo
結果:
曾孟良
1
陸燕
1