Redis for Mac安裝及使用


轉:https://www.jianshu.com/p/3b6bdf09a8ac

下載

https://redis.io/download

安裝

以Redis 5.0.5 版本為例

解壓 到你想放的目錄下(make 命令編譯文件)

cd  redis-5.0.5

make

 

打開終端輸入命令 啟動Redis 服務

src/redis-server

 

打開新的終端   運行客戶端

src/redis-cli

 

停止Redis服務

src/redis-cli shutdown

 

java 連接redis  以及讀寫數據(jedis 2.9.0.jar)

maven倉庫:https://mvnrepository.com/artifact/redis.clients/jedis

Redis支持五種數據類型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。

 

//連接本地的 Redis 服務

Jedis jedis =new Jedis("localhost");

System.out.println("連接成功");

//查看服務是否運行

System.out.println("服務正在運行: "+jedis.ping());

 

對象寫入Redis

1,序列化對象存儲; 2,json 字符串存儲

/**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;

}

 

序列化和反序列化對象工具

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 {

/**

* 序列化時必須要加上,否者反序列化會出錯

*/

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;

}

}

 
 
 
 



作者:alex_zj
鏈接:https://www.jianshu.com/p/3b6bdf09a8ac
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM