java 操作redis map_Java操作Redis存储HashMap对象类型数据

背景描述

关于JAVA去操作Redis时,如何存储一个对象的数据,这是大家非常关心的问题,虽然官方提供了存储String,List,Set等等类型,但并不满足我们现在实际应用。存储一个对象是非常常见的。经过网上查找资料以及参考其他网友的代码和实践操作后,整理出Redis如何存储一个Java的HashMap demo代码,如果有错误的地方大家可以留言指出。另外关于如果存储一个java对象可以参考上篇文章【Java操作Redis存储对象类型数据】https://blog.csdn.net/Chris_111X/article/details/85053544

参考资料

参考地址:

Bean代码

package com.obj.bean;

import java.io.Serializable;

public class Person implements Serializable {

/**

*

*/

private static final long serialVersionUID = 1L;

public String userName;

public String password;

public int age;

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}

测试代码

package com.java.client;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.Map.Entry;

import com.obj.bean.Person;

import redis.clients.jedis.Jedis;

public class RedisHashMapKey {

public static void main(String[] args) throws IOException, ClassNotFoundException {

// TODO Auto-generated method stub

Jedis redis = new Jedis("10.190.130.143", 6379);

redis.auth("sa123456");

Person p1 = new Person();

p1.setUserName("user1");

p1.setPassword("password1");

p1.setAge(10);

Person p2 = new Person();

p2.setUserName("user2");

p2.setPassword("password2");

p2.setAge(12);

Person p3 = new Person();

p3.setUserName("user3");

p3.setPassword("password3");

p3.setAge(13);

HashMap map = new HashMap();

map.put("p1", p1);

map.put("p2", p2);

map.put("p3", p3);

//转成输出字节流

ByteArrayOutputStream bai = new ByteArrayOutputStream();

ObjectOutputStream obi = new ObjectOutputStream(bai);

obi.writeObject(map);

byte[] byt = bai.toByteArray();

// 将map存入redis中

redis.set("p".getBytes(), byt);

//获取map

byte[] personByte = redis.get("p".getBytes());

ObjectInputStream oii = null;

ByteArrayInputStream bis = null;

//转换成输入字节流

bis = new ByteArrayInputStream(personByte);

oii = new ObjectInputStream(bis);

Map result = (Map) oii.readObject();

for (Entry entry : result.entrySet()) {

System.out.println("key= " + entry.getKey());

Person obj = (Person) entry.getValue();

System.out.println("getUserName: " + obj.getUserName());

System.out.println("getPassword= " + obj.getPassword());

System.out.println("getAge= " + obj.getAge());

}

}

}

运行结果

java 操作redis map_Java操作Redis存储HashMap对象类型数据_第1张图片

查看Redis

66b76a76983d8ec81da65d947fc7791f.png

你可能感兴趣的:(java,操作redis,map)