1 value的最基本的數據類型是String
2 如果value是一張圖片
先對圖片進行base64編碼成一個字符串,然后再保存到redis中,用的時候進行base64解碼即可。
這是base64的一個很典型的使用場景。
3 如果value是一個integer
使用Integer對象,然后將對象存儲在redis中。
4 如果value是一個float
用Float對象。
5 如果value是一個double
用Double對象。
6 如果value是一個對象
將對象轉換成byte[],然后保存到redis中,用的時候redis中讀取然后轉換即可。
The best way to do it is to use SerializationUtils from Apache Commons Lang.
不用自己寫。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency>
6.1 准備byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(yourObject); out.flush(); byte[] yourBytes = bos.toByteArray(); ... } finally { try { bos.close(); } catch (IOException ex) { // ignore close exception } }
6.2 獲取object
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); Object o = in.readObject(); ... } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } }
