---
title: "Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)"
author: "stephen830"
date: "2016-04-10T20:54:01Z"
tags: []
categories: ["移动开发"]
slug: "redis-jedis-java-java-byte"
draft: false
lastmod: "2016-04-10T20:57:04Z"
id: 2289920
url: "https://stephen830.iteye.com/blog/2289920"
---

Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)

 

在Jedis开发中，我们很多时候希望直接把一个对象放到Redis中，然后在需要的时候取出来。Redis的key和value都支持二进制安全的字符串，存储Java对象不是问题，下面我们看一下如何来实现。

 

# 1要存储的对象

现在写一个很土的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;

}

}
```

 

 

 

# 2序列化、反序列化

写一个序列化工具类，来提供对象的序列化和饭序列化的工作。代码如下：

```
/**
 * 序列化、反序列化工具类
 */
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;

	}

}
```

  

 

# 3写对象

将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));

}
```

 

# 4取对象

用Jedis获取对象：

```
public Person getObject(int id) {

byte[] person = jedis.get(("person:" + id).getBytes());

return (Person) SerializeUtil.unserialize(person);

}
```