Redis由于存入的数据类型有限,一般主要为字符串,通过key-value来存储数据,那么怎么通过Redis来写入和读取对象信息呢
写入数据
1.json方式
该方式使用Gson工具把对象转为字符串
static void write(){
//创建连接Redis的对象
Jedis jedis = new Jedis("localhost",6379);
//设置密码
jedis.auth("123");
//新建对象集合,实际项目中为数据库查到的常用但实时性不强的信息,作为缓存存入redis
List<User> list = new ArrayList<>();
list.add(new User(1, "tom", "tom"));
list.add(new User(2, "jack", "jack"));
list.add(new User(3, "lilei", "lilei"));
//新建Gson 对象,需要导Gson包
Gson gson = new Gson();
//转json字符串
String json = gson.toJson(list);
//往redis中放入数据,详细可参考Redis操作文档
jedis.set("list", json);
//释放
jedis.close();
}
序列化方式,对象需要实现Serializable
接口
static void write2() {
try {
Jedis jedis = new Jedis("localhost",6379);
jedis.auth("123");
List<User> list = new ArrayList<>();
list.add(new User(1, "tom", "tom"));
list.add(new User(2, "jack", "jack"));
list.add(new User(3, "lilei", "lilei"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] b = bos.toByteArray();
jedis.set("xlist".getBytes(), b);
jedis.close();
} catch (Exception e) {
// TODO: handle exception
}
}
读取数据
1.读取json数据
static void read(){
Jedis jedis = new Jedis("localhost",6379);
jedis.auth("123");
Gson gson = new Gson();
//读取存入redis中的key为list的数据
String string = jedis.get("list");
//转化简单数据
// User user = gson.fromJson(string,User.class);
//将读取到的json字符串转化为list集合
List<User> list = gson.fromJson(string,new TypeToken<List<User>>(){}.getType());
for (User user : list) {
System.out.println("姓名:"+user.getUname());
}
jedis.close();
}
2.序列化方式读
static void read2() {
try {
Jedis jedis = new Jedis("localhost",6379);
jedis.auth("123");
byte[] b = jedis.get("xlist".getBytes());
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInputStream ois = new ObjectInputStream(bis);
List<User> list = (List<User>) ois.readObject();
for (User user : list) {
System.out.println(user.getUname());
}
jedis.close();
} catch (Exception e) {
// TODO: handle exception
}
}