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

Source: Internet
Author: User
Tags key string

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

Learning Materials: 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"); // 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 <list. size (); I ++) {System. out. println (list. get (I);} // ----------- STRING ------------------ // SET key value associates the STRING value with the key. Jedis. set ("name", "yixiaohan"); jedis. set ("id", "007"); jedis. set ("address", "beijing"); // SETEX key seconds value associates the value with the key and sets the key's survival time to seconds (in seconds ). Jedis. setex ("foo", 5, "haha"); // MSET key value [key value...] simultaneously sets one or more key-value pairs. Jedis. mset ("kevin", "111", "keso", "222"); // redis. flushAll (); clears all keysystems. out. println ("dbSize =>" + 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 <getList. size (); I ++) {System. out. println (getList. get (I);} // DECR key: Reduce the number value stored in the key by one. // DECRBY key decrement: subtract the value stored in the key from the decrement. // INCR key adds the number value stored in the key to one. // INCRBY key increment adds the value stored in the key with the incremental increment. System. out. println ("\ n" + "================= Hash operation (key field value) ================== "); // HSET key field value sets the field value of the hash table key to 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...] set multiple field-value pairs to the hash table key. Map <String, String> map = new HashMap <String, String> (); 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 



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


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"]



References:

Http://try.redis.io/

Other network information, link to be added

Related Article

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.