Java Redis Jedis--學習筆記代碼片斷--序列化

來源:互聯網
上載者:User

Java Redis Jedis--學習筆記代碼片斷--序列化

維基百科 : Redis是一個開源、支援網路、基於記憶體、鍵值對儲存資料庫,使用ANSI C編寫。其開發由VMware主持。根據月度排行網站DB-Engines.com的資料顯示,Redis是最流行的鍵值對儲存資料庫。http://zh.wikipedia.org/wiki/Redis

學習資料:1 <<The Little Redis Book >> https://github.com/jarvischen/the-little-redis-book-cn/blob/master/cn/redis.md

package com.jiangge.jrtest;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import redis.clients.jedis.Jedis;public class JedisTest {public static void main(String[] args) {JedisTest jrd = new JedisTest();jrd.test();}public void test(){Jedis  jedis = new Jedis("localhost"); //串連redis  Jedis jedis = new Jedis("134.152.244.234",6379);  //redis.auth("redis"); //驗證密碼//jedis.flushAll(); //刪除所有key//Set keys = jedis.keys("*");//System.out.println(keys);jedis.set("test", "helloword!");jedis.set("foo", "foovaluehehehehe!");String value = jedis.get("test");System.out.println(value);//列出所有的key,尋找特定的key如:redis.keys("foo")    Set keys = jedis.keys("*");Iterator t1 = keys.iterator() ;while(t1.hasNext()){Object obj1 = t1.next();System.out.println(obj1);}//DEL 移除給定的一個或多個key。如果key不存在,則忽略該命令。Long delResult = jedis.del("name1");System.out.println("delResult ==>" + delResult);//TTL 返回給定key的剩餘存留時間(time to live)(以秒為單位)Long ttlResult = jedis.ttl("foo");System.out.println("ttlResult ==>" + ttlResult);//PERSIST key 移除給定key的存留時間。Long persistResult = jedis.persist("foo");System.out.println("persistResult ==>" + persistResult);//EXISTS 檢查給定key是否存在。Boolean existsResult = jedis.exists("foo");System.out.println("existsResult ==>" + existsResult);//MOVE key db  將當前資料庫(預設為0)的key移動到給定的資料庫db當中。如果當前資料庫(來源資料庫)和給定資料庫(目標資料庫)有相同名字的給定key,或者key不存在於當前資料庫,那麼MOVE沒有任何效果。jedis.move("foo", 1);//將foo這個key,移動到資料庫1//RENAME key newkey  將key改名為newkey。當key和newkey相同或者key不存在時,返回一個錯誤。當newkey已經存在時,RENAME命令將覆蓋舊值。jedis.rename("foo", "foonew");//TYPE key 返回key所儲存的值的類型。System.out.println("key所儲存的值的類型 ==>" + jedis.type("test"));//none(key不存在),string(字串),list(列表),set(集合),zset(有序集),hash(雜湊表)          //EXPIRE key seconds 為給定key設定存留時間。當key到期時,它會被自動刪除。jedis.expire("foo", 5);//5秒到期//EXPIREAT EXPIREAT的作用和EXPIRE一樣,都用於為key設定存留時間。不同在於EXPIREAT命令接受的時間參數是UNIX時間戳記(unix timestamp)。        //一般SORT用法 最簡單的SORT使用方法是SORT key。jedis.lpush("sort", "1");jedis.lpush("sort", "4");jedis.lpush("sort", "6");jedis.lpush("sort", "3");jedis.lpush("sort", "0");List list = jedis.sort("sort"); //預設是升序for(int i=0;i<list.size();i++){System.out.println(list.get(i));}//----------- STRING------------------// //SET key value將字串值value關聯到key。jedis.set("name", "yixiaohan");jedis.set("id", "007");jedis.set("address", "beijing");//SETEX key seconds value將值value關聯到key,並將key的存留時間設為seconds(以秒為單位)。jedis.setex("foo", 5, "haha");//MSET key value [key value ...]同時設定一個或多個key-value對。jedis.mset("kevin","111","keso","222"); //redis.flushAll();清空所有的keySystem.out.println("dbSize ==>" + jedis.dbSize());//dbSize是多少個key的個數//APPEND key value如果key已經存在並且是一個字串,APPEND命令將value追加到key原來的值之後。System.out.println("append before==>" + jedis.get("foo"));jedis.append("foo", "00");//如果key已經存在並且是一個字串,APPEND命令將value追加到key原來的值之後。System.out.println("append after==>" + jedis.get("foo"));//GET key 返回key所關聯的字串值String getResult = jedis.get("name");System.out.println("getResult==>" + getResult);//MGET key [key ...] 返回所有(一個或多個)給定key的值, 如果key不存在,則返回nullList getList = jedis.mget("address","name", "myboss");for(int i=0; i<getList.size(); i++){System.out.println(getList.get(i));}//DECR key 將key中儲存的數字值減一。//DECRBY key decrement 將key所儲存的值減去減量decrement。//INCR key 將key中儲存的數字值增一。//INCRBY key increment 將key所儲存的值加上增量increment。System.out.println("\n" + "==============Hash 操作(key field value)================");//HSET key field value將雜湊表key中的域field的值設為value。jedis.hset("website", "google", "www.google.cn");jedis.hset("website", "baidu", "www.baidu.com");jedis.hset("website", "sina", "www.sina.com");//HMSET key field value [field value ...] 同時將多個field - value(域-值)對設定到雜湊表key中。Map<String,String> map = new HashMap<String,String>();map.put("cardid", "123456");map.put("username", "yixiaohan");jedis.hmset("hash", map);//HGET key field返回雜湊表key中給定域field所對應的值。System.out.println("雜湊表key中給定域field所對應的值==>" + jedis.hget("hash", "username"));//HMGET key field [field ...]返回雜湊表key中,一個或多個給定域的值。List hlist = jedis.hmget("website","google","baidu","sina");for(int i=0;i<hlist.size();i++){System.out.println("hmget()返回雜湊表key中,一個或多個給定域的值==> " + hlist.get(i));}//HGETALL key返回雜湊表key中,所有的域和值。Map<String,String> allmap = jedis.hgetAll("hash");for(Map.Entry entry: allmap.entrySet()) {     System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");}//HDEL key field [field ...]刪除雜湊表key中的一個或多個指定域。//HLEN key 返回雜湊表key中域的數量。//HEXISTS key field查看雜湊表key中,給定域field是否存在。//HINCRBY key field increment為雜湊表key中的域field的值加上增量increment。//HKEYS key返回雜湊表key中的所有域。//HVALS key返回雜湊表key中的所有值。System.out.println("\n" + "==================== LIST 操作 ====================="); //LPUSH key value [value ...]將值value插入到列表key的表頭。//LPUSH puts the new value at the start of the listjedis.lpush("mylist", "abc");jedis.lpush("mylist", "xzc");jedis.lpush("mylist", "erf");jedis.lpush("mylist", "bnh");//LRANGE key start stop返回列表key中指定區間內的元素,區間以位移量start和stop指定。下標(index)參數start和stop都以0為底,//也就是說,以0表示列表的第一個元素,以1表示列表的第二個元素,以此類推。//你也可以使用負數下標,以-1表示列表的最後一個元素,-2表示列表的倒數第二個元素,以此類推。List listy = jedis.lrange("mylist", 0, -1);//LRANGE mylist 0 -1  ==> 其中 -1 返回所有的值.for(int i=0;i<listy.size();i++){System.out.println(listy.get(i));}System.out.println("列表key的長度==>" + jedis.llen("mylist"));//LLEN key返回列表key的長度。//LREM key count value根據參數count的值,移除列表中與參數value相等的元素。System.out.println("\n" + "===========  SET 操作 =====================");//SADD key member [member ...]將member元素加入到集合key當中。jedis.sadd("testSet", "s1");jedis.sadd("testSet", "s2");jedis.sadd("testSet", "s3");jedis.sadd("testSet", "s4");jedis.sadd("testSet", "s5");//SREM key member移除集合中的member元素。jedis.srem("testSet", "s5");//SMEMBERS key返回集合key中的所有成員。Set set = jedis.smembers("testSet");Iterator ite=set.iterator() ;while(ite.hasNext()){Object obj1=ite.next();System.out.println(obj1);}//SISMEMBER key member判斷member元素是否是集合key的成員。是(true),否則(false)boolean isInSet = jedis.sismember("testSet", "s4");System.out.println("sismember()判斷member元素是否是集合key的成員==>" + isInSet);//SCARD key返回集合key的基數(集合中元素的數量)。//SMOVE source destination member將member元素從source集合移動到destination集合。 //SINTER key [key ...]返回一個集合的全部成員,該集合是所有給定集合的交集。//SINTERSTORE destination key [key ...]此命令等同於SINTER,但它將結果儲存到destination集合,而不是簡單地返回結果集//SUNION key [key ...]返回一個集合的全部成員,該集合是所有給定集合的並集。//SUNIONSTORE destination key [key ...]此命令等同於SUNION,但它將結果儲存到destination集合,而不是簡單地返回結果集。//SDIFF key [key ...]返回一個集合的全部成員,該集合是所有給定集合的差集 。//SDIFFSTORE destination key [key ...]此命令等同於SDIFF,但它將結果儲存到destination集合,而不是簡單地返回結果集。}}



=====================================================================================


序列化:

Person.java

package com.jiangge.jrtest;import java.io.Serializable;@SuppressWarnings("serial")public class Person implements Serializable {    private int id;    private String name;    public Person() {    }    public Person(int id, String name) {        super();        this.id = id;        this.name = name;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}



PersonRedisSerializeTest.java

package com.jiangge.jrtest;import redis.clients.jedis.Jedis;public class PersonRedisSerializeTest {        public static void main(String[] args) {    PersonRedisSerializeTest test = new PersonRedisSerializeTest();    test.setObject(); //序列化    test.getObject(); //還原序列化    }    /**     * 序列化寫對象, 將Person對象寫入Redis中     *      * 我們到命令列視窗中讀取該對象,看看有沒有寫入成功:     *    redis 127.0.0.1:6379> get person:100     *    "\xac\xed\x00\x05sr\x00\x19com.jiangge.jrtest.Person\xfa\x13\xad$\x8e$\xfc\x80\x     *    02\x00\x02I\x00\x02idL\x00\x04namet\x00\x12Ljava/lang/String;xp\x00\x00\x00dt\x0     *    0\tyixiaohan"     * 可以取到序列化之後的值。     */    public void setObject() {    Jedis jedis=new Jedis("localhost");         jedis.set("person:100".getBytes(), SerializeUtil.serialize(new Person(100, "yixiaohan")));        jedis.set("person:101".getBytes(), SerializeUtil.serialize(new Person(101, "xiaowei")));    }            /** 還原序列化取對象 */    public void getObject() {    Jedis jedis=new Jedis("localhost");         byte[] data100= jedis.get(("person:100").getBytes());        Person person100 = (Person) SerializeUtil.unserialize(data100);        System.out.println(String.format("person:100->id=%s,name=%s", person100.getId(), person100.getName()));                byte[] data101= jedis.get(("person:101").getBytes());        Person person101 = (Person) SerializeUtil.unserialize(data101);        System.out.println(String.format("person:101->id=%s,name=%s", person101.getId(), person101.getName()));    }        }


SerializeUtil.java 

package com.jiangge.jrtest;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class SerializeUtil {    /**     * 序列化     * @param object     */    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;    }        /**     * 還原序列化     * @param bytes     */    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;    }}


啟動 redis server:




執行序列化代碼後,在 redis client中查看結果:




IDE控制台輸出結果:



=====================================================================================

Redis: key-value NoSQL Database


SET server:name "fido"
GET server:name


SET connections 10
INCR connections => 11
INCR connections => 12
DEL connections
INCR connections => 1


 DEL to delete a given key and associated value
  SET-if-not-exists (called SETNX on Redis) 
   INCR to atomically increment a number stored at a given key


an atomic operation 原子操作
an atomic operation concepts
h multi-threaded environments
所謂原子操作是指不會被線程調度機制打斷的操作;這種操作一旦開始,就一直運行到結束,中間不會有任何 context switch (切換到另一個線程)




 a key should only exist for a certain length of time. This is accomplished with the EXPIRE and TTL commands.
 key 存活於指定的時間,時間到則銷亡
 You can test how long a key will exist for with the TTL command
 TTL命令: key 還將存活多長時間 返回給定key的剩餘存留時間(time to live)(以秒為單位)


 complex data structures
 資料結構:
 list列表:相關命令, RPUSH, LPUSH, LLEN, LRANGE, LPOP, RPOP
RPUSH puts the new value at the end of the list.結尾
RPUSH friends "Alice"


LPUSH puts the new value at the start of the list.開頭
LPUSH friends "Sam"


LRANGE gives a subset of the list,給定範圍內的值.其中 -1 返回所有的值.
LRANGE friends 0 -1 => ["Sam","Alice","Bob"]
LRANGE friends 0 1 => ["Sam","Alice"]
LRANGE friends 1 2 => ["Alice","Bob"]




LLEN returns the current length of the list.返回當前列表的長度
   LLEN friends => 3




LPOP removes the first element from the list and returns it.刪除並返回列表中第一個值
   LPOP friends => "Sam"




RPOP removes the last element from the list and returns it.刪除並返回列表中最後一個值
   RPOP friends => "Bob"


Note that the list now only has one element:
   LLEN friends => 1
   LRANGE friends 0 -1 => ["Alice"]




set集合:相關命令: SADD, SREM, SISMEMBER, SMEMBERS, SUNION
SADD adds the given value to the set.添加
    SADD superpowers "flight"
    SADD superpowers "x-ray vision"
    SADD superpowers "reflexes"


SREM removes the given value from the set.刪除
    SREM superpowers "reflexes"


SISMEMBER tests if the given value is in the set.查看是否在集合中,也即查看是否是集合的成員
    SISMEMBER superpowers "flight" => true,1
    SISMEMBER superpowers "reflexes" => false,0


SMEMBERS returns a list of all the members of this set.返回集合中所有的成員,以列表的形式返回.
    SMEMBERS superpowers => ["flight","x-ray vision"]


SUNION combines two or more sets and returns the list of all elements.將多個集合合并
    SADD birdpowers "pecking"
    SADD birdpowers "flight"
    SUNION superpowers birdpowers => ["flight","x-ray vision","pecking"]

the sorted set有序集合. It is similar to a regular set, but now each value has an associated score標記.
This score is used to sort the elements in the set.
    ZADD hackers 1940 "Alan Kay"
    ZADD hackers 1906 "Grace Hopper"
    ZADD hackers 1953 "Richard Stallman"
    ZADD hackers 1965 "Yukihiro Matsumoto"
    ZADD hackers 1916 "Claude Shannon"
    ZADD hackers 1969 "Linus Torvalds"
    ZADD hackers 1957 "Sophie Wilson"
    ZADD hackers 1912 "Alan Turing"


In these examples, the scores are years of birth and the values are the names of famous hackers.
    ZRANGE hackers 2 4 => ["Claude Shannon", "Alan Kay","Richard Stallman"]



參考資料:

http://try.redis.io/

其他網路資料,有待把連結補充進來

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.