Redisオブジェクトインスタンスの保存

3658 ワード

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;
	}
}