下載
https://redis.io/download
安裝
以Redis 5.0.5 版本為例
解壓 到你想放的目錄下(make 命令編譯文件)
cd ?redis-5.0.5
make
打開(kāi)終端輸入命令 啟動(dòng)Redis 服務(wù)
src/redis-server
打開(kāi)新的終端 ? 運(yùn)行客戶端
src/redis-cli
停止Redis服務(wù)
src/redis-cli shutdown
java 連接redis ?以及讀寫(xiě)數(shù)據(jù)(jedis 2.9.0.jar)
maven倉(cāng)庫(kù):https://mvnrepository.com/artifact/redis.clients/jedis
Redis支持五種數(shù)據(jù)類型:string(字符串),hash(哈希)老厌,list(列表)盯串,set(集合)及zset(sorted set:有序集合)浮庐。
//連接本地的 Redis 服務(wù)
Jedis jedis =new Jedis("localhost");
System.out.println("連接成功");
//查看服務(wù)是否運(yùn)行
System.out.println("服務(wù)正在運(yùn)行: "+jedis.ping());
對(duì)象寫(xiě)入Redis
1抱慌,序列化對(duì)象存儲(chǔ); 2,json 字符串存儲(chǔ)
/**set Object*/
public String set(String key,Object object)
{
? ? ? ? ? ? ? ?return jedis.set(key.getBytes(), SerializeUtil.serialize(object));
}
/**get Object*/
public Object get(String key)
{
byte[] value =jedis.get(key.getBytes());
? ? ? ? ? ? ?return SerializeUtil.unSerialize(value);
}
/**delete a key**/
public boolean del(String key)
{
? ? ? ? ? ? ? return jedis.del(key.getBytes())>0;
}
序列化和反序列化對(duì)象工具
public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos =null;
ByteArrayOutputStream baos =null;
try {
? ? ? ? ? ? // 序列化
? ? ? ? ? ? baos =new ByteArrayOutputStream();
? ? ? ? ? ? oos =new ObjectOutputStream(baos);
? ? ? ? ? ? oos.writeObject(object);
? ? ? ? ? ? ?byte[] bytes = baos.toByteArray();
? ? ? ? ? ? return bytes;
}catch (Exception e) {
? ? ? ? ? ?e.printStackTrace();
}
return null;
}
public static Object unSerialize(byte[] bytes) {
ByteArrayInputStream bais =null;
try {
? ? ? ? ? ? ?// 反序列化
? ? ? ? ? ? bais =new ByteArrayInputStream(bytes);
? ? ? ? ? ? ?ObjectInputStream ois =new ObjectInputStream(bais);
? ? ? ? ? ? ?return ois.readObject();
}catch (Exception e) {
? ? ? ? ? ? ?e.printStackTrace();
}
return null;
}
}
static class Aaimplements Serializable {
/**
* 序列化時(shí)必須要加上,否者反序列化會(huì)出錯(cuò)
*/
private static final long serialVersionUID = -4470319009692911196L;
private String name;
private Integer age;
private Integer sex;
public String getName() {
? ? ? ? ? ?return name;
}
public void setName(String name) {
? ? ? ? ? ?this.name = name;
}
public Integer getAge() {
? ? ? ? ? ? return age;
}
public void setAge(Integer age) {
? ? ? ? ? ?this.age = age;
}
public Integer getSex() {
? ? ? ? ? ? return sex;
}
public void setSex(Integer sex) {
? ? ? ? ? ? this.sex = sex;
}
}