songsong0 2016-04-10
Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)
在Jedis开发中,我们很多时候希望直接把一个对象放到Redis中,然后在需要的时候取出来。Redis的key和value都支持二进制安全的字符串,存储Java对象不是问题,下面我们看一下如何来实现。
现在写一个很土的Java Bean,包含两个字段,id和name,类名叫做Person。为了实现序列化需求,该类实现Serializable接口。
public class Person implements Serializable {
private int id;
private String name;
 
public Person(int id, String name) {
this.id = id;
this.name = name;
}
 
public int getId() {
return id;
}
 
public String getName() {
return name;
}
}写一个序列化工具类,来提供对象的序列化和饭序列化的工作。代码如下:
/**
 * 序列化、反序列化工具类
 */
package com.stephen.utility;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
	/**
	 * 序列化
	 * 
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				bais.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
将Person对象写入Redis中:
public void setObject() {
Person person = new Person(100, "alan");
jedis.set("person:100".getBytes(), SerializeUtil.serialize(person));
person = new Person(101, "bruce");
jedis.set("person:101".getBytes(), SerializeUtil.serialize(person));
}用Jedis获取对象:
public Person getObject(int id) {
byte[] person = jedis.get(("person:" + id).getBytes());
return (Person) SerializeUtil.unserialize(person);
} Redis哨兵模式是Redis高可用方案的一种实现方式,通过哨兵来自动实现故障转移,从而保证高可用。-- lettuce客户端需要使用到 -->. application.yml哨兵模式配置属性示例。