redis中键值对中值的各种类型

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
  }
}


 

posted @ 2018-03-19 16:24  PhoenixTree(梧桐树)  阅读(2021)  评论(0编辑  收藏  举报