JavaRedisJedis -- learning note code snippet -- serialization

Source: Internet
Author: User
Tags key string set set
JavaRedisJedis-learning note code snippet-serialization Wikipedia: Redis is an open-source, network-supported, memory-based, key-Value Pair storage database written using ANSIC. Its development is hosted by VMware. Redis is the most popular key-Value Pair storage database, according to the data of the monthly ranking website DB-Engines.com. Zh. wikip

Java Redis Jedis-learning note code snippet-serialization Wikipedia: Redis is an open-source, network-supported, memory-based, key-Value Pair storage database written in ansi c. Its development is hosted by VMware. Redis is the most popular key-Value Pair storage database, according to the data of the monthly ranking website DB-Engines.com. Http://zh.wikip

Java Redis Jedis -- learning note code snippets -- serialization

Wikipedia: Redis is an open-source, network-supported, memory-based,Key-Value Pair storage database, Which is written in ansi c. Its development is hosted by VMware. Redis is the most popular, according to the monthly ranking site DB-Engines.com dataKey-value pairsStorage database. Http://zh.wikipedia.org/wiki/Redis

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"); // connect to redis Jedis jedis = new Jedis ("134.152.244.234", 6379 ); // Redis. auth ("redis"); // verify the password // jedis. flushAll (); // delete all keys // 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); // list all keys and find specific keys such as redis. keys ("foo") Set keys = jedis. keys ("*"); Iterator t1 = keys. iterator (); while (t1.hasNext () {Object obj1 = t1.next (); System. out. println (obj1);} // DEL removes one or more given keys. If the key does not exist, ignore this command. Long delResult = jedis. del ("name1"); System. out. println ("delResult =>" + delResult); // TTL returns the remaining time (time to live) of the given key (in seconds) Long ttlResult = jedis. ttl ("foo"); System. out. println ("ttlResult =>" + ttlResult); // The survival time for removing a given key from the PERSIST key. Long persistResult = jedis. persist ("foo"); System. out. println ("persistResult =>" + persistResult); // EXISTS checks whether a given key EXISTS. Boolean existsResult = jedis. exists ("foo"); System. out. println ("existsResult =>" + existsResult); // MOVE the key of the current database (0 by default) to the database. If the current database (source database) and the given database (target database) have a given key with the same name, or the key does not exist in the current database, moving has no effect. Jedis. move ("foo", 1); // move the key foo to database 1 // RENAME key newkey to change the key to newkey. If the key and newkey are the same or do not exist, an error is returned. When newkey already exists, the RENAME Command overwrites the old value. Jedis. rename ("foo", "foonew"); // TYPE key returns the TYPE of the value stored in the key. System. out. println ("type of the value stored by the key =>" + jedis. type ("test"); // none (key does not exist), string (string), list (list), set (set), zset (sorted set ), hash (hash table) // EXPIRE key seconds sets the survival time for the given key. When the key expires, it is automatically deleted. Jedis. expire ("foo", 5); // expired in 5 seconds // EXPIREAT works the same as EXPIRE and is used to set the survival time for the key. The difference is that the time parameter accepted by the EXPIREAT command is UNIX timestamp ). // Generally, the simplest SORT method is 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"); // The default value is ascending for (int I = 0; I
 
  
"+ Jedis. dbSize (); // dbSize is the number of keys // APPEND key value if the key already exists and is a string, the APPEND Command appends the value to the original value of the key. System. out. println ("append before =>" + jedis. get ("foo"); jedis. append ("foo", "00"); // if the key already exists and is a string, the APPEND Command appends the value to the original value of the key. System. out. println ("append after ==>" + jedis. get ("foo"); // GET key returns the String value associated with the key String getResult = jedis. get ("name"); System. out. println ("getResult =>" + getResult); // MGET key [key...] returns the values of all (one or more) specified keys. If the key does not exist, nullList getList = jedis is returned. mget ("address", "name", "myboss"); for (int I = 0; I
  
   
Map = new HashMap
   
    
(); Map. put ("cardid", "123456"); map. put ("username", "yixiaohan"); jedis. hmset ("hash", map); // HGET key field returns the value of the given field in the hash table key. System. out. println ("the value of the field in the given field in the hash table key =>" + jedis. hget ("hash", "username"); // hmet key field [field...] returns the values of one or more given fields in the hash table key. List hlist = jedis. hmet ("website", "google", "baidu", "sina"); for (int I = 0; I
    
     
"+ Hlist. get (I);} // HGETALL key returns all the fields and values in the hash table key. Map
     
      
Allmap = jedis. hgetAll ("hash"); for (Map. entry entry: allmap. entrySet () {System. out. print (entry. getKey () + ":" + entry. getValue () + "\ t");} // HDEL key field [field...] deletes one or more specified fields in the hash table key. // HLEN key returns the number of fields in the hash table key. // Check whether the specified field exists in the hash table key in HEXISTS key field. // HINCRBY key field increment adds incremental increment to the field value in the hash table key. // HKEYS key returns all fields in the hash table key. // HVALS key returns all values in the hash table key. System. out. println ("\ n" + "======================== LIST Operation ========== ============ "); // LPUSH key value [value...] insert the value to the header of the list 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"); // The LRANGE key start stop operation returns the elements in the specified range of the list key. The range is specified by the offset start and stop. Both the start and stop parameters of the subscript (index) are based on 0. // That is to say, 0 indicates the first element of the list, 1 indicates the second element of the List, and so on. // You can also use a negative subscript to represent the last element of the list in-1,-2 in the last element of the List, and so on. List listy = jedis. lrange ("mylist", 0,-1); // LRANGE mylist 0-1 ==> where-1 returns all values. for (int I = 0; I
      
        "+ Jedis. llen (" mylist "); // The length of the list key returned by LLEN key. // LREM key count value removes the elements in the list that are equal to the parameter value based on the value of the parameter count. System. out. println ("\ n" + "=========== SET operation ====================== = "); // SADD key member [member...] add the member element to the set key. Jedis. sadd ("testSet", "s1"); jedis. sadd ("testSet", "s2"); jedis. sadd ("testSet", "s3"); jedis. sadd ("testSet", "s4"); jedis. sadd ("testSet", "s5"); // the SREM key member removes the member element from the set. Jedis. srem ("testSet", "s5"); // SMEMBERS key returns all members in the set key. Set set = jedis. smembers ("testSet"); Iterator ite = set. iterator (); while (ite. hasNext () {Object obj1 = ite. next (); System. out. println (obj1);} // SISMEMBER key member determines whether the member element is a member of the set key. Yes (true); otherwise (false) boolean isInSet = jedis. sismember ("testSet", "s4"); System. out. println ("sismember () determines whether the member element is a member of the set key =>" + isInSet); // The SCARD key returns the base number of the set key (the number of elements in the set ). // SMOVE source destination member moves the member element from the source set to the destination set. // SINTER key [key...] returns all the members of a set, which is the intersection of all the given sets. // SINTERSTORE destination key [key...] this command is equivalent to SINTER, But it saves the result to the destination set, instead of simply returning the result set // SUNION key [key...] returns all members of a set, which is the union of all given sets. // SUNIONSTORE destination key [key...] This command is equivalent to SUNION, But it saves the result to the destination set instead of simply returning the result set. // SDIFF key [key...] returns all the members of a set, which is the difference set of all given sets. // SDIFFSTORE destination key [key...] This command is equivalent to SDIFF, But it saves the result to the destination set instead of simply returning the result set .}}
      
     
    
   
  
 

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

Serialization:

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 (); // serialize test. getObject (); // deserialization}/*** serialize and write the Person object to Redis. ** read the object in the command line window to see if the object has been written successfully: * redis 127.0.0.1: 6379> get person: 100 * "\ xac \ xed \ x00 \ x05sr \ x00 \ x19com. jiangge. jrt Est. 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 "* can get the serialized value. */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");}/** deserialization object */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 {/*** serialize * @ param object */public static byte [] serialize (Object object) {ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try {// serialize baos = new ByteArrayOutputStream (); oos = new ObjectOutputStream (baos); oos. writeObject (object); byte [] bytes = baos. toByteArray (); return bytes;} catch (Exception e) {e. printStackTrace ();} return null;}/*** deserialization * @ param bytes */public static Object unserialize (byte [] bytes) {ByteArrayInputStream bais = null; try {// deserialization bais = new ByteArrayInputStream (bytes); ObjectInputStream ois = new ObjectInputStream (bais); return ois. readObject ();} catch (Exception e) {e. printStackTrace ();} return null ;}}
Start redis server:


After the serialization code is executed, view the result in redis client:

IDE console output result:

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

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
The so-called atomic operation is an operation that will not be interrupted by the thread scheduling mechanism. Once this operation starts, it will continue to run until the end, and there will be no context switch (switch to another thread) in the middle)

A key shoshould only exist for a certain length of time. This is accomplished with the EXPIRE and TTL commands.
The key is alive at the specified time, and the sales will die when the time reaches.
You can test how long a key will exist for with the TTL command
TTL command: how long will the key survive? returns the time to live of the given key (in seconds)

Complex data structures
Data structure:
List: related commands, RPUSH, LPUSH, LLEN, LRANGE, LPOP, RPOP
RPUSH puts the new value at the end of the list. end
RPUSH friends "Alice"

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

LRANGE gives a subset of the list, values in the given range.-1 returns all values.
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. returns the length of the current list
LLEN friends => 3

LPOP removes the first element from the list and returns it. Delete and return the first value in the list.
LPOP friends => "Sam"

RPOP removes the last element from the list and returns it. Delete and return the last value in the list.
RPOP friends => "Bob"

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

Set: related commands: SADD, SREM, SISMEMBER, SMEMBERS, SUNION
SADD adds the given value to the set. Add
SADD superpowers "flight"
SADD superpowers "x-ray vision"
SADD superpowers "reflexes"

SREM removes the given value from the set. Delete
SREM superpowers "reflexes"

SISMEMBER tests if the given value is in the set. check whether it is in the set, that is, whether it is a member of the set.
SISMEMBER superpowers "flight" => true, 1
SISMEMBER superpowers "reflexes" => false, 0

SMEMBERS returns a list of all the members of this set. all the members in the set are returned in the form of a list.
SMEMBERS superpowers => ["flight", "x-ray vision"]

SUNION combines two or more sets and returns the list of all elements. Merge multiple sets
SADD birdpowers "pecking"
SADD birdpowers "flight"
SUNION superpowers birdpowers => ["flight", "x-ray vision", "pecking"]

The sorted set ordered set. It is similar to a regular set, but now each value has an associated score tag.
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 "clude 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 => ["clude Shannon", "Alan Kay", "Richard Stallman"]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.