redis中如何存儲java對象


根據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;
    }


}

 

方法2:將java對象轉換為json字符串,利用json與java對象之間可以相互轉換的方式進行存值和取值
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM