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. 百度编辑器 Ueditor 如何增加字体 ?

    在百度编辑器 Ueditor 如何增加字体 ? 要修改两个文件: 第一个文件:editor-config.js: ,'fontfamily':[             { label:'',name ...

  2. 算法(Algorithms)第4版 练习 1.5.23

    package com.qiusongde; import edu.princeton.cs.algs4.StdOut; public class Exercise1523 { public stat ...

  3. IE Firefox css 差别

    1.单位问题 问题:任何距离的数值ie可以不加单位,ff必须要求写单位(0除外) 解决:写全单位如padding:0px; 2.水平居中 问题:div里的内容,ie默认为center,而ff默认lef ...

  4. LightOJ 1138 二分

    1138 - Trailing Zeroes (III)   PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: ...

  5. 使用ajax与iframe嵌套实现页面局部刷新

    使用ajax与iframe嵌套实现页面局部刷新.该javascript代码仅供参考,需按自己需要修改.​1. [代码]javascript代码 function cj_start(depname,gr ...

  6. NET 平台下的WebService 简单使用

    一句话理解:提供可供外部访问的方法,实现跨平台访问 注意: 在客户端是添加“服务引用”,而不是引用 当服务端更新了服务之后,在客户端,一定也要“更新服务” 当要执行异常调用时,要在前台.aspx的头部 ...

  7. Android 之 Matrix(转)

    原文:http://www.cnblogs.com/qiengo/archive/2012/06/30/2570874.html#code Android Matrix   Matrix的数学原理 平 ...

  8. Python-单元测试unittest

    Python中有一个自带的单元测试框架是unittest模块,用它来做单元测试,它里面封装好了一些校验返回的结果方法和一些用例执行前的初始化操作,概念见下: TestCase 也就是测试用例 Test ...

  9. 【遍历二叉树】05二叉树的层次遍历II【Binary Tree Level Order Traversal II】

    就把vector改成用栈类存放层次遍历的一层的序列 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ...

  10. JavaScript RegExp 正则表达式基础详谈

    前言: 正则对于一个码农来说是最基础的了,而且在博客园中,发表关于讲解正则表达式的技术文章,更是数不胜数,各有各的优点,但是就是这种很基础的东西,如果我们不去真正仔细研究.学习.掌握,而是抱着需要的时 ...