一、到目前为止(jedis-2.2.0.jar),在Jedis中其实并没有提供这样的API对对象,或者是List对象的直接缓存,即并没有如下类似的API

jedis.set(String key, Object value)

jedis.set(String key, List<M> values)

而更多的API是类似于 jedis.set(String key, String value)或者jedis.set(String key, String ... value)

那如果我们想缓存对象,怎么办呢?

二、通过研究Jedis的API,我们发现其提供了这样的API

jedis.set(byte[], byte[]),

通过这个API,很显然我们能够实现

jedis.set(String key, Object value)

jedis.set(String key, List<M> values)

我们需要关注的就是在cache的时候将Object和List对象转换成字节数组并且需要提供将字节数组转换成对象返回。

三、考虑到扩展性,设计了3个类,抽象父类SerializeTranscoder, 子类ListTranscoder和ObjectsTranscoder 以及一个Unit test 类 用于模拟对象,list对象和字节数组的转换,即Serialize和de-searilize的过程。

1. SerializeTranscoder

package com.chuanliu.platform.activity.basic.util.serialize;

import java.io.Closeable;

import org.apache.log4j.Logger;

/**
* @author Josh Wang(Sheng)
*
* @email josh_wang23@hotmail.com
*/
public abstract class SerializeTranscoder { protected static Logger logger = Logger.getLogger(SerializeTranscoder.class); public abstract byte[] serialize(Object value); public abstract Object deserialize(byte[] in); public void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
logger.info("Unable to close " + closeable, e);
}
}
}
}

2. ListTranscoder

package com.chuanliu.platform.activity.basic.util.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; import com.chuanliu.platform.activity.basic.util.LoggerUtils; /**
* Case 1.
* Jedis does not support cache the Object directly, the Objects needed to be
* serialized and de-serialized
*
* Case 2.
* coming very soon...
*
* @author Josh Wang(Sheng)
*
* @email josh_wang23@hotmail.com
*/
public class ListTranscoder<M extends Serializable> extends SerializeTranscoder { @SuppressWarnings("unchecked")
public List<M> deserialize(byte[] in) {
List<M> list = new ArrayList<>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
while (true) {
M m = (M)is.readObject();
if (m == null) {
break;
} list.add(m); }
is.close();
bis.close();
}
} catch (IOException e) {
LoggerUtils.error(logger, String.format("Caught IOException decoding %d bytes of data",
in == null ? 0 : in.length) + e);
} catch (ClassNotFoundException e) {
LoggerUtils.error(logger, String.format("Caught CNFE decoding %d bytes of data",
in == null ? 0 : in.length) + e);
} finally {
close(is);
close(bis);
} return list;
} @SuppressWarnings("unchecked")
@Override
public byte[] serialize(Object value) {
if (value == null)
throw new NullPointerException("Can't serialize null"); List<M> values = (List<M>) value; byte[] results = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null; try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (M m : values) {
os.writeObject(m);
} // os.writeObject(null);
os.close();
bos.close();
results = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
} return results;
} }

3. ObjectsTranscoder

package com.chuanliu.platform.activity.basic.util.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; import com.chuanliu.platform.activity.basic.util.LoggerUtils; /**
* Case 1.
* Jedis does not support cache the Object directly, the Objects needed to be
* serialized and de-serialized
*
* Case 2.
* coming very soon...
*
* @author Josh Wang(Sheng)
*
* @email josh_wang23@hotmail.com
*/
public class ObjectsTranscoder<M extends Serializable> extends SerializeTranscoder { @SuppressWarnings("unchecked")
@Override
public byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] result = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
M m = (M) value;
os.writeObject(m);
os.close();
bos.close();
result = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return result;
} @SuppressWarnings("unchecked")
@Override
public M deserialize(byte[] in) {
M result = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
result = (M) is.readObject();
is.close();
bis.close();
}
} catch (IOException e) {
LoggerUtils.error(logger, String.format("Caught IOException decoding %d bytes of data",
in == null ? 0 : in.length) + e);
} catch (ClassNotFoundException e) {
LoggerUtils.error(logger, String.format("Caught CNFE decoding %d bytes of data",
in == null ? 0 : in.length) + e);
} finally {
close(is);
close(bis);
}
return result;
}
}

4. TestSerializerTranscoder

package com.chuanliu.platform.activity.basic.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; import org.junit.Test; import com.chuanliu.platform.activity.basic.util.serialize.ListTranscoder;
import com.chuanliu.platform.activity.basic.util.serialize.ObjectsTranscoder; /**
* @author Josh Wang(Sheng)
*
* @email josh_wang23@hotmail.com
*/
public class TestSerializerTranscoder implements Serializable { private static final long serialVersionUID = -1941046831377985500L; public TestSerializerTranscoder() { } @Test
public void testObject() {
List<TestUser> lists = buildTestData(); TestUser userA = lists.get(0); ObjectsTranscoder<TestUser> objTranscoder = new ObjectsTranscoder<>(); byte[] result1 = objTranscoder.serialize(userA); TestUser userA_userA = objTranscoder.deserialize(result1); System.out.println(userA_userA.getName() + "\t" + userA_userA.getAge());
} @Test
public void testList() {
List<TestUser> lists = buildTestData(); ListTranscoder<TestUser> listTranscoder = new ListTranscoder<>(); byte[] result1 = listTranscoder.serialize(lists); List<TestUser> results = listTranscoder.deserialize(result1); for (TestUser user : results) {
System.out.println(user.getName() + "\t" + user.getAge());
} } private static List<TestUser> buildTestData() {
TestSerializerTranscoder tst = new TestSerializerTranscoder();
TestUser userA = tst.new TestUser();
userA.setName("lily");
userA.setAge(25); TestUser userB = tst.new TestUser(); userB.setName("Josh Wang");
userB.setAge(28); List<TestUser> list = new ArrayList<TestUser>();
list.add(userA);
list.add(userB); return list;
} class TestUser implements Serializable {
private static final long serialVersionUID = 1L; private String name; private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} } }

四、通过以上几步后,即可使用Jedis的API进行对象的缓存并将从缓存中返回的二进制数组转换成原始的对象或者是List对象了。

Redis缓存Object,List对象的更多相关文章

  1. redis缓存怎么存储对象

    2.把对象Object存储到redis中,怎么存?memcache存取对象是序列化和反序列化 使用通用的序列化.反序列化(频繁的会很消耗cpu,使用Google Protocol Buffer,将对象 ...

  2. SpringBoot缓存管理(二) 整合Redis缓存实现

    SpringBoot支持的缓存组件 在SpringBoot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.spri ...

  3. Redis缓存 ava-Jedis操作Redis,基本操作以及 实现对象保存

    源代码下载: http://download.csdn.net/detail/jiangtao_st/7623113 1.Maven配置 <dependency> <groupId& ...

  4. Redis缓存 序列化对象存储乱码问题

    使用Redis缓存对象会出现下图现象: 键值对都是乱码形式. 解决以上问题: 如果是xml配置的 我们直接注入官方给定的keySerializer,valueSerializer,hashKeySer ...

  5. Redis缓存系统(一)Java-Jedis操作Redis,基本操作以及 实现对象保存

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/jiangtao_st/article/details/37699473 源码下载: http://d ...

  6. SpringBoot使用redis缓存List<Object>

    一.概述 最近在做性能优化,之前有一个业务是这样实现的: 1.温度报警后第三方通讯管理机直接把报警信息保存到数据库 2.我们在数据库中添加触发器,(BEFORE INSERT)根据这条报警信息处理业务 ...

  7. Redis缓存系统-Java-Jedis操作Redis,基本操作以及 实现对象保存

    源代码下载:   http://download.csdn.net/detail/jiangtao_st/7623113 1.Maven配置 <dependency> <groupI ...

  8. springboot redis 缓存对象

    只要加入spring-boot-starter-data-redis , springboot 会自动识别并使用redis作为缓存容器,使用方式如下 gradle加入依赖 compile(" ...

  9. 缓存工厂之Redis缓存

    这几天没有按照计划分享技术博文,主要是去医院了,这里一想到在医院经历的种种,我真的有话要说:医院里的医务人员曾经被吹捧为美丽+和蔼+可亲的天使,在经受5天左右相互接触后不得不让感慨:遇见的有些人员在挂 ...

随机推荐

  1. [办公自动化]EXCEL不大,但是保存很慢

    今天同事有一个excel文件.office 2007格式的. 折腾了半天.按照以往的经验,定位-对象,应该可以删除. 后来在“编辑”窗格的“查找和选择”里面,单击“选择窗格“.可以看到很多”pictu ...

  2. high-level operations on files and collections of files

    11.10. shutil — High-level file operations — Python 3.6.5 documentation https://docs.python.org/3/li ...

  3. diy数据库(二)--网络通信类

    一.首先,我们先实现OSS层的ossSocket类.供数据库client和数据库引擎进行通信 友情提示:相应上面的类图的头文件和源码附在了本文的最以下. int _fd ;//socket的文件描写叙 ...

  4. 网络驱动移植之net_device结构体及其相关的操作函数

    内核源码:Linux-2.6.38.8.tar.bz2 在Linux系统中,网络设备都被抽象为struct net_device结构体.它是网络设备硬件与上层协议之间联系的接口,了解它对编写网络驱动程 ...

  5. URAL1099 Work Scheduling —— 一般图匹配带花树

    题目链接:https://vjudge.net/problem/URAL-1099 1099. Work Scheduling Time limit: 0.5 secondMemory limit: ...

  6. 《MIDINET: A CONVOLUTIONAL GENERATIVE ADVERSARIAL NETWORK FOR SYMBOLIC-DOMAIN MUSIC GENERATION》论文阅读笔记

    出处 arXiv.org (引用量暂时只有3,too new)2017.7 SourceCode:https://github.com/RichardYang40148/MidiNet Abstrac ...

  7. mysql 联合2个列的数据 然后呈现出来

    SELECT a.voyageNum,CONCAT(a.startDate,'~',a.endDate) AS 日期  FROM tchw_voyageoilcost a ,tchw_voyageoi ...

  8. UVa 12709 && UVaLive 6650 Falling Ants (水题)

    题意:给定 n 个长方体的长,宽,高,让你求高最大的时候体积最大是多少. 析:排序,用高和体积排序就好. 代码如下: #pragma comment(linker, "/STACK:1024 ...

  9. Linux 常用命令四 rmdir rm

    一.rmdir命令 用于删除空目录: wang@wang:~/workpalce/python$ tree . ├── .txt ├── .txt ├── .txt ├── A │   └── B │ ...

  10. bzoj 2288: 【POJ Challenge】生日礼物【链表+堆】

    参考:http://blog.csdn.net/w_yqts/article/details/76037315 把相同符号的连续数字加起来,合并后ans先贪心的加上所有正数,如果正数个数sum> ...