首页>代码>Spring MVC+bootstrap+redis+mybatis整合开发开源高并发秒杀商品系统>/seckill/src/main/java/org/seckill/dao/cache/RedisDao.java
package org.seckill.dao.cache; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.runtime.RuntimeSchema; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.seckill.entity.Seckill; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * Created by wchb7 on 16-5-27. */ public class RedisDao { private final Log LOG = LogFactory.getLog(this.getClass()); 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) { //redis逻辑操作 try { Jedis jedis = jedisPool.getResource(); try { String key = "seckill:" + seckillId; //并没有实现内部序列化操作 //get:byte[]->反序列化->Object(Seckill) //采用自定义序列化 byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { //空对象 Seckill seckill = schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, seckill, schema); //seckill 被反序列化 return seckill; } } finally { jedis.close(); } } catch (Exception e) { LOG.error(e.getMessage()); } return null; } /** * Seckill 对象传递到redis中 * * @param seckill * @return */ public String putSeckill(Seckill seckill) { //set:Object(Seckill)->序列化->byte[] ->发送给redis try { Jedis jedis = jedisPool.getResource(); try { String key = "seckill:" + seckill.getSeckillId(); byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); //超时缓存 int timeOut = 60 * 60; String result = jedis.setex(key.getBytes(), timeOut, bytes); return result; } finally { jedis.close(); } } catch (Exception e) { LOG.error(e.getMessage()); } return null; } }
最近下载更多
dapeng0011 LV13
2月24日
笛卡尔积 LV6
2023年2月17日
弹指又十年 LV8
2022年9月18日
asd6260647 LV4
2022年7月2日
moneyla LV5
2022年3月11日
李可以 LV5
2022年2月19日
xuweisong2010 LV27
2021年10月28日
qiheideguang LV16
2021年10月17日
ltq50736 LV4
2021年9月3日
qiangmin1223 LV12
2021年8月25日
最近浏览更多
dapeng0011 LV13
2月24日
limin123 LV6
2023年10月16日
西瓜哥哥 LV4
2023年8月16日
yqyqyqyqy LV4
2023年8月10日
cunbie LV4
2023年6月13日
aaaahao LV13
2023年5月29日
杨亚洲
2023年5月5日
暂无贡献等级
aaaaooa LV4
2023年4月22日
微信网友_6442962125967360 LV2
2023年4月21日
1613619109 LV6
2023年3月24日