Redis没有直接存储对象的方法,不过Redis要以存储字节,所以可以先把对象自己写的一个序列化和反序列化的方法
-
package com.comtop;
-
-
import java.io.ByteArrayInputStream;
-
import java.io.ByteArrayOutputStream;
-
import java.io.ObjectInputStream;
-
import java.io.ObjectOutputStream;
-
import java.io.Serializable;
-
-
import org.junit.Before;
-
import org.junit.Test;
-
-
import redis.clients.jedis.Jedis;
-
import redis.clients.jedis.JedisPool;
-
import redis.clients.jedis.JedisPoolConfig;
-
-
/**
-
* @ProjectName:Skeleton
-
* @PackageName:com.comtop
-
* @Verson :0.1
-
* @CreateUser :Test
-
* @CreateDate :2014-7-19上午10:47:11
-
* @UseFor :
-
*/
-
public class JedisTest {
-
JedisPool pool;
-
Jedis jedis;
-
-
@Before
-
public void setUp() {
-
JedisPoolConfig config = new JedisPoolConfig();
-
pool = new JedisPool(config, "127.0.0.1");
-
jedis = pool.getResource();
-
// 密码验证
-
jedis.auth("password");
-
}
-
-
@Test
-
public void test() throws InterruptedException {
-
Person person = new Person("123", "alan");
-
jedis.set("person:123".getBytes(), SerializeUtil.ObjTOSerialize(person));
-
person = new Person("234", "bruce");
-
jedis.set("person:234".getBytes(), SerializeUtil.ObjTOSerialize(person));
-
-
Person per = getObject("234");
-
System.out.println(per);
-
}
-
-
private Person getObject(String id) {
-
byte[] person = jedis.get(("person:" + id).getBytes());
-
return (Person) SerializeUtil.unSerialize(person);
-
}
-
}
-
-
class Person implements Serializable {
-
private static final long serialVersionUID = 1L;
-
private String id;
-
private String name;
-
-
/**
-
* @param id
-
* @param name
-
*/
-
Person(String id, String name) {
-
super();
-
this.id = id;
-
this.name = name;
-
}
-
-
public String getId() {
-
return id;
-
}
-
-
public void setId(String id) {
-
this.id = id;
-
}
-
-
public String getName() {
-
return name;
-
}
-
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
@Override
-
public String toString()
-
{
-
return this.id +" "+this.name ;
-
}
-
}
-
-
class SerializeUtil {
-
-
/**
-
*
-
* @CreateUser:
-
* @ReturnType:byte[]
-
* @param obj
-
* @return
-
* @CreateDate:2014-7-19上午11:38:19
-
* @SerializeUtilUseFor :序列化一个对象
-
*/
-
public static byte[] ObjTOSerialize(Object obj) {
-
ObjectOutputStream oos = null;
-
ByteArrayOutputStream byteOut = null;
-
try {
-
byteOut = new ByteArrayOutputStream();
-
oos = new ObjectOutputStream(byteOut);
-
oos.writeObject(obj);
-
byte[] bytes = byteOut.toByteArray();
-
return bytes;
-
} catch (Exception e) {
-
}
-
return null;
-
}
-
-
/**
-
*
-
* @CreateUser:Test
-
* @ReturnType:Object
-
* @param bytes
-
* @return
-
* @CreateDate:2014-7-19上午11:38:29
-
* @SerializeUtilUseFor :反序列化
-
*/
-
public static Object unSerialize(byte[] bytes) {
-
ByteArrayInputStream in = null;
-
try {
-
in = new ByteArrayInputStream(bytes);
-
ObjectInputStream objIn = new ObjectInputStream(in);
-
return objIn.readObject();
-
} catch (Exception e) {
-
}
-
return null;
-
}
-
}