Redis不支持直接将Java对象存储到数据库中,所以需要将java对象进行序列化得到字节数组,然后将字节数组存入到redis中,需要数据的时候就从redis数据库中取出字节数组,再经过反序列化将自己数组转换成对象使用(jdk序列化性能比谷歌公司的Protobuf序列化性能要差一些,而且序列化后的字节长度要也会长一些,所以推荐使用Protobuf,Protobuf如何进行序列化请看我的另一篇帖子)
实体类
User.java
1. import java.io.Serializable;
2. public class User implements Serializable{
3. private static final long serialVersionUID = 2724888087391664167L;
4. private String id;
5. private String username;
6. private String password;
7. public User() {
8. }
9. public User(String id, String username, String password) {
10. this.id = id;
11. this.username = username;
12. this.password = password;
13. }
14. public String getId() {
15. return id;
16. }
17. public void setId(String id) {
18. this.id = id;
19. }
20. public String getUsername() {
21. return username;
22. }
23. public void setUsername(String username) {
24. this.username = username;
25. }
26. public String getPassword() {
27. return password;
28. }
29. public void setPassword(String password) {
30. this.password = password;
31. }
32. public static long getSerialversionuid() {
33. return serialVersionUID;
34. }
35. @Override
36. public String toString() {
37. return "User [id=" + id + ", username=" + username + ", password="
38. + password + "]";
39. }
40. }
序列化反序列化工具类
SerializeUtils.java
1. import java.io.ByteArrayInputStream;
2. import java.io.ByteArrayOutputStream;
3. import java.io.IOException;
4. import java.io.ObjectInputStream;
5. import java.io.ObjectOutputStream;
6. public class SerializeUtils {
7. public static byte[] serialize(Object obj){
8. byte[] bytes = null;
9. try {
10. ByteArrayOutputStream baos=new ByteArrayOutputStream();;
11. ObjectOutputStream oos=new ObjectOutputStream(baos);
12. oos.writeObject(obj);
13. bytes=baos.toByteArray();
14. baos.close();
15. oos.close();
16. } catch (IOException e) {
17. e.printStackTrace();
18. }
19. return bytes;
20. }
21. public static Object deSerialize(byte[] bytes){
22. Object obj=null;
23. try {
24. ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
25. ObjectInputStream ois=new ObjectInputStream(bais);
26. obj=ois.readObject();
27. } catch (Exception e) {
28. e.printStackTrace();
29. }
30. return obj;
31. }
32. }
测试类RedisTest.java
1. import java.util.HashMap;
2. import java.util.List;
3. import java.util.Map;
4. import java.util.Set;
5. import org.junit.Test;
6. import redis.clients.jedis.Jedis;
7. public class RedisTest{
8. private static Jedis jedis;
9. static{
10. //访问本地redis
11. jedis = new Jedis("127.0.0.1",6379);
12. }
13. @Test
14. public void serialize(){
15. User user=new User("1000", "宝宝", "xioabao");
16. jedis.set(user.getId().getBytes(), SerializeUtils.serialize(user));
17. byte[] bytes=jedis.get(user.getId().getBytes());
18. System.out.println((User)SerializeUtils.deSerialize(bytes));
19. }
20. }