根據redis的存儲原理,Redis的key和value都支持二進制安全的字符串
1.利用序列化和反序列化的方式
存儲java對象我們可以通過對象的序列化與反序列化完成存儲於取出,這樣就可以使用redis存儲java對象了
a.利用jdk自帶的序列化機制,但效率不高
步驟:創建一個序列化和反序列化的工具類
public class SerializeUtil { public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { //序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { } return null; } public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { //反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } }
b.利用谷歌的序列化依賴,高效,使用於秒殺等業務場景
<!--prostuff序列化依賴 -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
</dependency>
@Slf4j public class RedisDao { private final JedisPool jedisPool; private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class); public RedisDao(String ip, int port) { jedisPool = new JedisPool(ip, port); } public Seckill getSeckill(Long seckillId) { Jedis jedis = null; try { jedis = jedisPool.getResource(); String key = "seckill:" + seckillId; byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { Seckill seckill = schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, seckill, schema); return seckill; } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } return null; } public String putSeckill(Seckill seckill) { Jedis jedis = null; try { jedis = jedisPool.getResource(); String key = "seckill:" + seckill.getSeckillId(); byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); Integer timeout = 60 * 60; String result = jedis.setex(key.getBytes(), timeout, bytes); return result; } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } return null; } }