1、Redis可以用来存储Java对象,Jedis有一个方法
String redis.clients.jedis.BinaryJedis.set(byte[] key, byte[] value)
Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
Time complexity: O(1)
key和value都是字节数组
2、自定义对象必须实现序列化接口
public class TestObj **implements Serializable**{
public TestObj(){
}
public TestObj(int age,String name){
this.age =age;
this.name = name;
}
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "TestObj=[age=" + this.age + ",name="+ this.name+"]";
}
}
(1)必须实现序列化接口,必须实现序列化接口!!!!!
(2)序列化是针对【对象】而言,类的静态成员是类级别的,不参与序列化!!!
(3)如果想要某个成员不被序列化,可以用transient修饰
3、序列化反序列化代码
public class ObjectUtils
{
/**
* 序列化
* @param object
* @return
*/
public static byte[] serialize(Object object)
{
if (object == null)
{
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try
{
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
}
catch (Exception e)
{
RedisLog.error("序列化异常", e);
return null;
}
finally
{
if (oos != null)
{
try
{
oos.close();
}
catch (IOException e)
{
RedisLog.error("序列化关闭oos异常", e);
}
}
if (baos != null)
{
try
{
baos.close();
}
catch (IOException e)
{
RedisLog.error("序列化关闭baos异常", e);
}
}
}
}
/**
* 反序列化
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes)
{
if (bytes == null)
{
return null;
}
ObjectInputStream ois = null;
ByteArrayInputStream bais = null;
try
{
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (Exception e)
{
RedisLog.error("反序列化异常", e);
return null;
}
finally
{
if (ois != null)
{
try
{
ois.close();
}
catch (IOException e)
{
RedisLog.error("反序列化关闭ois异常", e);
}
}
if (bais != null)
{
try
{
bais.close();
}
catch (IOException e)
{
RedisLog.error("反序列化关闭bais异常", e);
}
}
}
}
}