【redis对象,集合序列化Demo】
package org.seckill.dao.cache;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import org.seckill.entity.Seckill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
public class RedisDao2 {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private final JedisPool jedisPool;
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);//自定义schema
RedisDao2(String ip, int port){
jedisPool = new JedisPool(ip, port);
}
public Seckill getSeckill(long seckillId) {
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "" + seckillId;
byte[] bs = jedis.get(key.getBytes());
if (bs != null) {
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bs,seckill,schema);//反序列化
return seckill;
}
} finally{
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}
//对象序列化:
public String putSeckill(Seckill seckill) {
try {
Jedis jedis = jedisPool.getResource();
try {
String key = ""+ seckill.getSeckillId();
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema,LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)/*缓存器*/);// 序列化到二进制数组
int timeOut = 60 * 60 ;// 单位是s:缓存1h
String result = jedis.setex(key.getBytes(), timeOut , bytes);
return result;
} finally{
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}
public Seckill getSeckillAll() {
RuntimeSchema<Seckill> schema = (RuntimeSchema<Seckill>) RuntimeSchema.getSchema(Seckill.class);
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckillList";
byte[] bs = jedis.get(key.getBytes());
if (bs != null) {
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bs,seckill,schema);//反序列化
return seckill;
}
} finally{
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}
//集合序列化:
private <T> byte[] serializeList(List<T> objList) {
if (objList == null || objList.isEmpty()) {
throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
}
@SuppressWarnings("unchecked")
RuntimeSchema<T> schema = (RuntimeSchema<T>) RuntimeSchema.getSchema(objList.get(0).getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protostuff = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
protostuff = bos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
} finally {
buffer.clear();
try {
if(bos!=null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return protostuff;
}
private <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
}
RuntimeSchema<T> schema = (RuntimeSchema<T>) RuntimeSchema.getSchema(targetClass);
List<T> result = null;
try {
result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
} catch (IOException e) {
throw new RuntimeException("反序列化对象列表发生异常!",e);
}
return result;
}
//集合反序列化:
public <T> String putSeckillAll(List<T> objList) {
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckillAllList:001";
int timeOut = 60 * 60 ;// 单位是s:缓存1h
byte[] serializeList = serializeList(objList);
String result = jedis.setex(key.getBytes(), timeOut , serializeList);
return result;
} finally{
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
//byte[] serializeList = serializeList(objList);
}
//集合序列化:
public <T> List<T> getSeckillAllList(Class<T> targetClass) {
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckillAllList:001";
byte[] bs = jedis.get(key.getBytes());
if (bs != null) {
@SuppressWarnings("unchecked")
List<T> deserializeList = (List<T>) deserializeList(bs,targetClass);
return deserializeList;
}
} finally{
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}
}
【redis对象,集合序列化Demo】的更多相关文章
- Redis对象——集合(Set)
集合类型 (Set) 是一个无序并唯一的键值集合.它的存储顺序不会按照插入的先后顺序进行存储. 集合类型和列表类型的区别如下: 列表可以存储重复元素,集合只能存储非重复元素: 列表是按照元素的先后顺序 ...
- Redis对象——有序集合(ZSet)
有序集合类型 (Sorted Set或ZSet) 相比于集合类型多了一个排序属性 score(分值),对于有序集合 ZSet 来说,每个存储元素相当于有两个值组成的,一个是有序结合的元素值,一个是排序 ...
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...
- Intent之对象传递(Parcelable传递对象和对象集合)
接着上一篇文章,以下我们讨论一下怎样利用Parcelable实现Intent之间对象的传递 一.实现对象传递 首先创建User.java实现Parcelable接口: package org.yayu ...
- (记录)Jedis存放对象和读取对象--Java序列化与反序列化
一.理论分析 在学习Redis中的Jedis这一部分的时候,要使用到Protostuff(Protobuf的Java客户端)这一序列化工具.一开始看到序列化这些字眼的时候,感觉到一头雾水.于是,参考了 ...
- [Android学习]Activity之间传递对象和对象集合
开发过程中,Activity之间传递数据是必不可少的,android中使用Intent和Bundle作为数据载体,在Activity之间传递,对于基础数据类型,Bundle已经提供相关的put,get ...
- 【Java IO流】对象的序列化和反序列化
对象的序列化和反序列化 1)对象序列化,就是将Object对象转换成byte序列,反之叫对象的反序列化. 2)序列化流(ObjectOutputStream),是字节的过滤流—— writeObjec ...
- 【redis源码阅读】redis对象
结构定义 在redis中,对象的数据结构定义如下: typedef struct redisObject { unsigned type:4; unsgined encoding:4; uns ...
- JAVA之旅(三十)——打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码
JAVA之旅(三十)--打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码 三十篇了,又是一个 ...
随机推荐
- HDU3294 Girls' research
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000 作者博客:http://www.cnblogs.com/ljh2000-jump/ ...
- jquery详解图片平滑滚动
jquery详解图片平滑滚动 随便写了个DOM,没有美观性,见谅 原理: 1.定义两组ul列表放图,第一个ul放5张图,第二个ul为空 2.为什么要用两个ul?因为要用到jQuery的克隆方法clon ...
- redis实现session共享,哨兵
一.Redis介绍 1.redis是key-value的存储系统,属于非关系型数据库 2.特点:支持数据持久化,可以让数据在内存中保存到磁盘里(memcached:数据存在内存里,如果服务重启,数据会 ...
- Android之setContentView和LayoutInflater
setContentView: 1.常用的构造函数: 1)setContentView(int layoutResID) 2)setContentView(View view) 3)setConten ...
- C++ 0X 新特性实例(比较常用的) (转)
转自:http://www.cnblogs.com/mrblue/p/3141456.html //array #include <array> void Foo1() { array&l ...
- AAC_LC用LATM封装header信息解析 Audio Specific Config格式分析
通常来说AAC的头信息在编解码过程中是可以获取到的,但今天需要根据音频参数生成相应的AAC头.项目中使用的是AAC_LC,今天先对它的结构进行分析. 项目中使用ffmpeg进行音频编码,音频编码库为F ...
- URAL1517Freedom of Choice(后缀数组)
Background Before Albanian people could bear with the freedom of speech (this story is fully describ ...
- 【LeetCode】024. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. For example,Given 1->2-&g ...
- 用WinDbg分析Debug Diagnostic Tool生成的Userdump文件
1.下载WinDbg(Debugging Tools for Windows):http://www.microsoft.com/whdc/devtools/debugging/default.msp ...
- bzoj 2716 天使玩偶 —— K-D树
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2716 果然和 bzoj 2648 是一样的吧: 只是数组要迷之开大,3e5+5 会RE? 代 ...