数据库
首页 > 数据库> > redis中如何存储java对象

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对象之间可以相互转换的方式进行存值和取值

标签:存储,序列化,java,bytes,redis,seckill,jedis,return,null
来源: https://www.cnblogs.com/panbingqi/p/11341601.html