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. UVA 1664 Conquer a New Region (并查集+贪心)

    并查集的一道比较考想法的题 题意:给你n个点,接着给你n-1条边形成一颗生成树,每条边都有一个权值.求的是以一个点作为特殊点,并求出从此点出发到其他每个点的条件边权的总和最大,条件边权就是:起点到终点 ...

  2. C# 多服务器上传 示例

    图片服务器  带宽越来越不够用,还有当一台服务器的机房出问题的时候,不影响 整个web,以及 考虑网通电信访问服务器的 速度,所以考虑使用多台 图片 服务器 这个时候要求 图片服务器 内容是同步 的  ...

  3. 初学Linux笔记

    自动获取IP地址的局域网中,用的是DHCP服务器

  4. asp.net中异步调用WebService(异步页)[转]

    由于asp2.0提供了异步页的支持使异步调用WebService的性能有了真正的提升.使用异步页,首先要设置Async="true",异步页是在Prerender和Prerende ...

  5. java支付宝开发-异常-01-"sub_code":"isv.invalid-app-id","sub_msg":"无效的AppID参数"

    一.现象 无论请求哪个接口都报这个错误 二.异常原因 后来检查了一下,发现是因为 我支付宝网关写错了.沙箱环境和正式环境 的支付宝网关不同,如下 //支付宝网关名-正式环境 //public stat ...

  6. Java钉钉开发_02_免登授权(身份验证)

    源码已上传GitHub: https://github.com/shirayner/DingTalk_Demo 一.本节要点 1.免登授权的流程 (1)签名校验 (2)获取code,并传到后台 (3) ...

  7. 【前端】【javascript】es6中的遍历器接口Iterator

    好久没发文章啦-.-为了证明我还活着,我决定从笔记里面抓一篇还算不乱比较像文章的发出来... 这些笔记是我在学es6的时候断断续续记录的,最近会一份一份整理陆陆续续发出来,顺便也自己再看一遍.我学习e ...

  8. codeforces 710C C. Magic Odd Square(构造)

    题目链接: C. Magic Odd Square Find an n × n matrix with different numbers from 1 to n2, so the sum in ea ...

  9. javascript设计模式和构造函数返回值

    工厂模式 function createPerson(name,age,job){ var o = new Object(); o.name = name; o.age = age; o.job = ...

  10. MySQL 和 InnoDB

    发现一篇总结的很不错的文章,转一下 (原文作者:Draveness   原文链接:https://draveness.me/mysql-innodb) 作为一名开发人员,在日常的工作中会难以避免地接触 ...