1. 首先创建一个Product类,并实现序列化
import java.io.Serializable;
//将类的对象按照字符串格式存到redis
public class Product implements Serializable{
private String name;
private int price;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "product:名称: "+name + " 价格: "+ price+" 描述: "+ desc;
}
}
Redis实现:
import com.google.gson.Gson;
import redis.clients.jedis.Jedis;
import java.io.*;
public class StringDemo {
private static Jedis jedis = new Jedis("192.168.88.130",6379);
//字符串缓存
public static void StringTest(){
jedis.set("user:01:name","kate");
//mset写多行数据
jedis.mset("user:02:name","mary","user:03:name","candy");
//根据key取值
String name1 = jedis.get("user:01:name");
String name2 = jedis.get("user:02:name");
String name3 = jedis.get("user:03:name");
System.out.println(name1);
System.out.println(name2);
System.out.println(name3);
jedis.close();
}
//存对象,到字符串数结构
public static void objectTest()throws Exception{
Product product = new Product();
product.setName("Apple");
product.setPrice(5);
product.setDesc("很甜");
//将对象进行序列化
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
//把对象写到输出流里面
oos.writeObject(product);
//将序列化好的对象数据存到一个String类型的数组里面
byte[] bproduct = baos.toByteArray();
jedis.set("product01".getBytes(),bproduct);
byte[] resbyte = jedis.get("product01".getBytes());
//反序列化
ByteArrayInputStream bais = new ByteArrayInputStream(resbyte);
ObjectInputStream ois = new ObjectInputStream(bais);
Product products = (Product)ois.readObject();
//打印结果
System.out.println(products);
jedis.close();
}
//对象以json的形式写入
public static void objectToJsonTest(){
Product product = new Product();
product.setName("Apple phone");
product.setPrice(5);
product.setDesc("很贵");
//把对象转变成一个json
Gson gson = new Gson();
String jsonObject = gson.toJson(product);
jedis.set("product02",jsonObject);
String jsonStr =jedis.get("product02");
//把json里面对象取出来
Product res = gson.fromJson(jsonStr,Product.class);
System.out.println(res);
jedis.close();
}
public static void main(String[] args) throws Exception {
// StringTest();
objectTest();
//objectToJsonTest();
}
}
/*
product:名称: Apple 价格: 5 描述: 很甜
*/
启动redis
/usr/local/redis/bin/redis-server /usr/local/redis/bin/redis.conf
/usr/local/redis/bin/redis-cli -h 127.0.0.1 -p 6379