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】的更多相关文章

  1. Redis对象——集合(Set)

    集合类型 (Set) 是一个无序并唯一的键值集合.它的存储顺序不会按照插入的先后顺序进行存储. 集合类型和列表类型的区别如下: 列表可以存储重复元素,集合只能存储非重复元素: 列表是按照元素的先后顺序 ...

  2. Redis对象——有序集合(ZSet)

    有序集合类型 (Sorted Set或ZSet) 相比于集合类型多了一个排序属性 score(分值),对于有序集合 ZSet 来说,每个存储元素相当于有两个值组成的,一个是有序结合的元素值,一个是排序 ...

  3. Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解

    一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...

  4. Intent之对象传递(Parcelable传递对象和对象集合)

    接着上一篇文章,以下我们讨论一下怎样利用Parcelable实现Intent之间对象的传递 一.实现对象传递 首先创建User.java实现Parcelable接口: package org.yayu ...

  5. (记录)Jedis存放对象和读取对象--Java序列化与反序列化

    一.理论分析 在学习Redis中的Jedis这一部分的时候,要使用到Protostuff(Protobuf的Java客户端)这一序列化工具.一开始看到序列化这些字眼的时候,感觉到一头雾水.于是,参考了 ...

  6. [Android学习]Activity之间传递对象和对象集合

    开发过程中,Activity之间传递数据是必不可少的,android中使用Intent和Bundle作为数据载体,在Activity之间传递,对于基础数据类型,Bundle已经提供相关的put,get ...

  7. 【Java IO流】对象的序列化和反序列化

    对象的序列化和反序列化 1)对象序列化,就是将Object对象转换成byte序列,反之叫对象的反序列化. 2)序列化流(ObjectOutputStream),是字节的过滤流—— writeObjec ...

  8. 【redis源码阅读】redis对象

    结构定义 在redis中,对象的数据结构定义如下: ​typedef struct redisObject { ​unsigned type:4; ​unsgined encoding:4; ​uns ...

  9. JAVA之旅(三十)——打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码

    JAVA之旅(三十)--打印流PrintWriter,合并流,切割文件并且合并,对象的序列化Serializable,管道流,RandomAccessFile,IO其他类,字符编码 三十篇了,又是一个 ...

随机推荐

  1. HDU 4714 Tree2cycle:贪心

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4714 题意: 给你一棵树,添加和删除一条边的代价都是1.问你将这棵树变成一个环的最小代价. 题解: 贪 ...

  2. 英语发音规则---/ŋ/与/ŋg/的读音区别

    英语发音规则---/ŋ/与/ŋg/的读音区别 一.总结 一句话总结: 1.位于词中间的字母组合ng,有时读作/ ŋ /,有时读作/ ŋg/? singer ['sɪŋə] n. 歌手 ringing ...

  3. java:Map借口及其子类HashMap四

    java:Map借口及其子类HashMap四 使用非系统对象作为key,使用匿名对象获取数据 在Map中可以使用匿名对象找到一个key对应的value. person: public class Ha ...

  4. Unity3D之Mesh【创建动态Mesh的学习网站】

    觉得不错!做记录! 1.http://gamerboom.com/archives/76484 2.http://jayelinda.com/ 3.几个私人的博客,可能有启发:http://blog. ...

  5. adb命令(二)

    1.获取手机型号指令 adb shell cat /system/build.prop | findstr "ro.product.model" 2.获取手机处理器信息 adb s ...

  6. 数学建模--matlab基础知识

    虽然python也能做数据分析,不过参加数学建模,咱还是用专业的 1. Matlab-入门篇:Hello world! 程序员入门第一式: disp(‘hello world!’) 2. 基本运算 先 ...

  7. python中类__call__方法与@classmethod

    实现了__call__方法的类就变成了一个可调用对象,可以像函数一样调用,callable(obj)就返回True,否则返回False. 参考:https://www.cnblogs.com/supe ...

  8. codeforces 553A A. Kyoya and Colored Balls(组合数学+dp)

    题目链接: A. Kyoya and Colored Balls time limit per test 2 seconds memory limit per test 256 megabytes i ...

  9. POJ-1564 dfs

    #include"cstring" #include"cstdio" +; int nux[maxn]; int nua[maxn];//解的集合 int t; ...

  10. 问题6:如何让字典保持有序(使用collections的OrderedDict方法)

    from collections imort OrderedDict d = OrderedDict() d['aa'] = (1, 30) d['bb'] = (2, 31) d['cc'] = ( ...