Jedis的方法基本和Redis的指令一一对应。
把一个对象写入Redis:
package com.qiuqiu.jedis;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
try (Jedis jedis = new Jedis("123.57.61.22", 6379)) {
jedis.select(0);
Country china = new Country("china", "beijing", 960);
Country jiangSu = new Country("jiangsu", "nanjing", 40);
List<Country> list = new ArrayList<>();
list.add(jiangSu);
china.setChildren(list);
String str = JSONObject.toJSONString(china);
System.out.println(str);
jedis.set("country#001", str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Country {
private String name;
private String capital;
private int size;
List<Country> children;
public Country(String name, String capital, int size) {
this.name = name;
this.capital = capital;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Country> getChildren() {
return children;
}
public void setChildren(List<Country> children) {
this.children = children;
}
}
从Redis中读取一个对象:
public class Test {
public static void main(String[] args) {
try (Jedis jedis = new Jedis("123.57.61.22", 6379)) {
jedis.select(0);
String str = jedis.get("country#001");
Country country = JSONObject.parseObject(str, Country.class);
System.out.println(country);
} catch (Exception e) {
e.printStackTrace();
}
}
}