package cn.xiyou.entity;
import java.io.Serializable;
/**
* User实体
*
* @author XIOAHU
*
*/
public class User implements Serializable {
private static final long serialVersionUID = -5811774997813073219L;
private String name;
private Integer age;
private Character gender;// 数据类型请忽略,只为测试
public User() {
}
public User(String name, Integer age, Character gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Character getGender() {
return gender;
}
public void setGender(Character gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", gender=" + gender
+ "]";
}
}
package cn.xiyou.entity;
import java.util.List;
/**
* Person实体类
*
* @author XIAOHU
*
*/
public class Person {
private String name;
private List<User> uList;
public Person() {
}
public Person(String name, List<User> uList) {
super();
this.name = name;
this.uList = uList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getuList() {
return uList;
}
public void setuList(List<User> uList) {
this.uList = uList;
}
@Override
public String toString() {
return "Person [name=" + name + ", uList=" + uList + "]";
}
}
redis其原生的jedis并没有实现内部序列化操作,不像memcached内部做了序列化。当高并发时,dk自带的序列化机制serializable效率比较低,序列化后的文件大, 故,采用开源社区提供protostuff,它提供的序列化机制效率较高。
protostuff把一个对象转化为二进制数组,存入redis中。当获取时,将得到的二进制数组byte[](对象或图片或文字存储形式都是二进制数组)反序列化得到Object对象。protostuff只需要知道这个对象是什么class,内部有一个schema描述这个class是什么结构。并要求该对象为POJO类型,即有getter、setter方法java对象。
package cn.xiyou.utils;
import java.util.List;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisClientUtil {
/**
* 连接池
*/
private static JedisPool pool;
static {
pool = new JedisPool("127.0.0.1", 6379);
}
/**
* Redis存储简单类型
*
* @param key
* @param value
* @return
*/
public static String set(String key, String value) {
Jedis jedis = pool.getResource();
String set = jedis.set(key, value);
jedis.close();
return set;
}
/**
* 获取Redis存储的简单类型
*
* @param key
* @return
*/
public static String get(String key) {
Jedis jedis = pool.getResource();
String value = jedis.get(key);
jedis.close();
return value;
}
/**
* ProtostuffIOUtil序列化对象并使用Redis存储
*
* @param key
* @param value
* @param type
* @return
*/
public static String setObject(String key, Object value, Class<?> type) {
Jedis jedis = pool.getResource();
byte[] byteKey = key.getBytes();
@SuppressWarnings("unchecked")
RuntimeSchema<Object> schema = (RuntimeSchema<Object>) RuntimeSchema
.createFrom(type);
// 序列化
byte[] bytes = ProtostuffIOUtil.toByteArray(value, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
String set = jedis.set(byteKey, bytes);
jedis.close();
return set;
}
/**
* ProtostuffIOUtil反序列对象并返回Redis中的对象
*
* @param key
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public static Object getObject(String key, Class<?> type) {
Jedis jedis = pool.getResource();
byte[] bytes = jedis.get(key.getBytes());
RuntimeSchema<Object> schema = (RuntimeSchema<Object>) RuntimeSchema
.createFrom(type);
Object result = schema.newMessage();// 创建空对象
ProtostuffIOUtil.mergeFrom(bytes, result, schema);// 把字节数组的数据存入result对象中
jedis.close();
return result;
}
}
package cn.xiyou.test;
import java.util.ArrayList;
import java.util.List;
import cn.xiyou.entity.Person;
import cn.xiyou.entity.User;
import cn.xiyou.utils.RedisClientUtil;
public class TestRedis {
public static void main(String[] args) {
/**
* 测试存储简单类型(String key : String value)
*/
RedisClientUtil.set("name", "zhang");
String name = RedisClientUtil.get("name");
System.out.println(name);// 输出:zhang
RedisClientUtil.set("age", "12");
String age = RedisClientUtil.get("age");
if (age != null) {
System.out.println(Integer.parseInt(age));// 输出:12
}
/**
* 测试存储简单JavaBean
*/
User u = new User("xiao", 18, '男');
RedisClientUtil.setObject("user", u, User.class);
User user1 = (User) RedisClientUtil.getObject("user", User.class);
System.out.println(user1);
// 输出:User [name=xiao, age=18, gender=男]
/**
* 存取List集合
* (以下测试失败)不能直接存储List集合,无法识别List存储的具体的存储类型
*/
/*
User u3 = new User("cai", 20, '女');
ArrayList aList = new ArrayList();
aList.add(u3);
RedisClientUtil.setObject("aList", aList, ArrayList.class);
@SuppressWarnings("unchecked")
ArrayList list2 = (ArrayList) RedisClientUtil.getObject(
"aList", ArrayList.class);
System.out.println(list2.get(0));// 报异常:java.lang.ArrayIndexOutOfBoundsException:0
for (Iterator it = list2.iterator(); it.hasNext();) {
User user = it.next();// 报异常:java.util.ConcurrentModificationException
System.out.println(user);
}
*/
/**
* 存取List集合
* 【第一种】建议将List集合封装成复杂JavaBean,即可。
*/
User u2 = new User("cai", 20, '女');
ArrayList<User> uList = new ArrayList<User>();
uList.add(u2);
Person p = new Person("哈哈", uList);
RedisClientUtil.setObject("p", p, Person.class);
Person pp = (Person) RedisClientUtil.getObject("p", Person.class);
System.out.println(pp);
// 输出:Person [name=哈哈, uList=[User [name=cai, age=20, gender=女]]]
/**
* 存储List集合
* 【第二种】使用fastjson将其转换为String存储,取时再转换成list即可。
*/
User u5 = new User("cai", 20, '女');
User u6 = new User("xiao", 18, '男');
ArrayList<User> list2 = new ArrayList<User>();
list2.add(u5);
list2.add(u6);
RedisClientUtil.set("list2", JSON.toJSONString(list2));
String jsonStr = RedisClientUtil.get("list2");
List<User> resultList = JSON.parseArray(jsonStr, User.class);
System.out.println("====");
System.out.println(resultList);
//输出:[User [name=cai, age=20, gender=女], User [name=xiao, age=18, gender=男]]
}
}
package cn.xiyou.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* 封装JDK提供的序列化
*
* @author XIAOHU
*
*/
public class JDKSerializeUtil {
/**
* 单个对象序列化
*
* @param object
* @return
*/
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 单个对象反序列化
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return null;
}
/**
* 序列化 list 集合
*
* @param list
* @return
*/
public static byte[] serializeList(List<?> list) {
if (list == null || list.size() == 0) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
for (Object obj : list) {
oos.writeObject(obj);
}
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 反序列化 list 集合
* @param bytes
* @return
*/
public static List<?> unserializeList(byte[] bytes) {
if (bytes == null) {
return null;
}
List<Object> list = new ArrayList<Object>();
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
while (bais.available() > 0) {
Object obj = (Object) ois.readObject();
if (obj == null) {
break;
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return list;
}
/**
* 关闭io流对象
*
* @param closeable 可用来关闭的数据的来源或目的地
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package cn.xiyou.utils;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisClientUtil {
/**
* 连接池
*/
private static JedisPool pool;
static {
pool = new JedisPool("127.0.0.1", 6379);
}
/**
* JDk序列对象并存储List集合
*
* @param key
* @param list
*/
public static void setList(String key, List<?> list) {
Jedis jedis = pool.getResource();
try {
if (list == null || list.size() == 0) {// 如果list为空,则设置一个空串""
jedis.set(key.getBytes(), "".getBytes());
} else {
jedis.set(key.getBytes(), JDKSerializeUtil.serializeList(list));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
/**
* JDK反序列对象并获取List集合
*
* @param key
* @return
*/
public static List<?> getList(String key) {
Jedis jedis = pool.getResource();
if (jedis == null || !jedis.exists(key)) {
return null;
}
byte[] data = jedis.get(key.getBytes());
jedis.close();
return JDKSerializeUtil.unserializeList(data);
}
}
package cn.xiyou.test;
import java.util.ArrayList;
import java.util.List;
import cn.xiyou.entity.Person;
import cn.xiyou.entity.User;
import cn.xiyou.utils.RedisClientUtil;
public class TestRedis {
public static void main(String[] args) {
/**
* 使用jdk提供的序列化,测试Redis存储List集合
*/
User u4 = new User("cai", 20, '女');
ArrayList<User> list = new ArrayList<User>();
list.add(u4);
RedisClientUtil.setList("ulist", list);
@SuppressWarnings("unchecked")
List<User> list111 = (List<User>) RedisClientUtil.getList("ulist");
System.out.println(list111);
// 输出:[User [name=cai, age=20, gender=女]]
}
}
commons-pool2-2.3.jar
jedis-2.7.0.jar
protostuff-api-1.4.4.jar
protostuff-collectionschema-1.4.4.jar
protostuff-core-1.4.4.jar
protostuff-runtime-1.4.4.jar
fastjson-1.2.47.jar