pom.xml文件引入依赖:
<!--protostuff序列化工具,效率和内存都很高-->
<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>
Redis.dao类中的使用:
public class RedisDao {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final JedisPool jedisPool;
private final String password;
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);
public RedisDao(String ip, int port,String password) {
jedisPool = new JedisPool(ip, port);
this.password = password;
}
/**
* 得到缓存中的seckill
*
* @param seckillId
* @return
*/
public Seckill getSeckill(long seckillId) {
//Redis操作逻辑
try {
Jedis jedis = jedisPool.getResource();
jedis.auth(password);
try {
String key = "seckill:" + seckillId;
//并没有实现内部序列化操作
//get->byte[]->反序列化->Object(Seckill)
//采用自定义序列化,将对象转换成二进制数组,传递给redis缓存起来
//protostuff : pojo
byte[] bytes = jedis.get(key.getBytes());
//缓存中获取到
if (bytes != null) {
//通过schema构造空对象
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
//seckill被反序列化
return seckill;
}
} finally {
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 如果缓存中没有,则put一个进去
*
* @param seckill
* @return
*/
public String putSeckill(Seckill seckill) {
try {
Jedis jedis = jedisPool.getResource();
jedis.auth(password);
try {
String key = "seckill:" + seckill.getSeckillId();
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//调用jedis.setex(key,timeout,bytes)
//超时缓存,缓存一小时
int timeout = 60*60;
String result = jedis.setex(key.getBytes(), timeout, bytes);
return result;
} finally {
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}