Redis对对象的操作

Redis是可以存放一个Java对象并获取的,用到的知识点就是Java的序列化机制。

1、编写序列化工具方法

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	
	public static byte[] serialize(Object object) throws IOException {
		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) {
			e.printStackTrace();
		}finally {
			baos.close();
			oos.close();
		}
		return null;
	}

	public static Object unserialize(byte[] bytes) throws IOException {
		ByteArrayInputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			bais.close();
		}
		return null;
	}
}

2、创建对象

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private int no;
	private String name;
	
	public Person(int no, String name) {
		super();
		this.no = no;
		this.name = name;
	}
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
3、编写Redis实现

import java.io.IOException;

import redis.clients.jedis.Jedis;

public class ObjectTest {

	public static void main(String[] args) {
		ObjectTest objectTest = new ObjectTest();
		//objectTest.add();
		objectTest.get();
	}
	
	public void add() {
		Jedis jedis = new Jedis("localhost", 6379);
		try {
			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));
			
			// redis 127.0.0.1:6379> get person:100
			// "\xac\xed\x00\x05sr\x00\x15alanland.redis...
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void get() {
		Jedis jedis = new Jedis("localhost", 6379);
		System.out.println(jedis.get("person:100")); // 这里是乱码
		byte[] personRedis = jedis.get(("person:100").getBytes());
		try {
			Person person = (Person)SerializeUtil.unserialize(personRedis);
			System.out.println(person.getNo());
			System.out.println(person.getName());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值