I. Introduction of Redis
Redis is an open source software written in C that can run on Linux and does not currently support windows. Redis is typically used for caching, data persistence, Message Queuing, and Redis avoids the loss of memory data after the server hangs up. Redis supports 5 types of data structures: strings, hashes, lists, sets, sorted sets, and the operations on these data structures are atomic, which means that the operations of these collections are thread-safe Redis first is to put the data set in memory, you can set every time to persist data to the hard disk, if the project only requires Redis cache, persistence can be banned; Redis supports master-slave synchronization like MySQL, Data on the primary server can be synchronized to n slave servers, and can be read and written separated.
Most programming languages can use REDIS,C, C + +, Java, C #, and Python to use Redis services to bind the IP and ports of the Redis server through the appropriate API. In the following chapters, we will take Java as an example to introduce simple operations on REDIS data structures.
Second, Redis supported data structure and simple operation
1. String
On the string data structure, Redis and memcached are consistent, supporting Key-value data storage (a key corresponding to a value, equivalent to HashMap in Java), support for a key to set a value, Supports adding a string after value under a certain key, deleting a specific key, and then adding or reducing an atom to the numeric value of the corresponding key.
Public classredisclient {Private Static FinalString host= "192.168.146.129"; Private Static Final intport=6379; Private FinalJedis jedis=NewJedis (Host,port); /*** Test Redis for key-value access*/@Test Public voidTestkeyvalue () {Jedis.set ("Name", "Boruoyihao"); System.out.println ("Get name from Redis:" +jedis.get ("name")); System.out.println ("is exist in Redis:" +jedis.exists ("name")); Jedis.append ("Name", ", Hello");//add under the same keySystem.out.println ("Get name from Redis:" +jedis.get ("name")); Jedis.del ("Name");//Delete the KeySystem.out.println ("Get name from Redis:" +jedis.get ("name")); //equivalent to Jedis.set ("name", "Boreyihao"); //Jedis.set ("age", +);Jedis.mset ("name", "Boreyihao", "Age", "26"); System.out.println (Jedis.get ("Name") + "= =" +jedis.get ("Age")); //set name valid for 2SJedis.setex ("Name", 2, "Boruo"); System.out.println ("Get name from Redis:" +jedis.get ("name")); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } //name time timeout, fetch data is nullSystem.out.println ("Get name from Redis:" +jedis.get ("name")); //Atomic increment OperationJedis.set ("Age", "26"); JEDIS.INCR ("Age"); System.out.println (' Get age from Redis: ' +jedis.get ("age")); Jedis.decrby ("Age", 3); System.out.println (' Get age from Redis: ' +jedis.get ("age")); }}
2. Hashes
A redis hash can be stored as a key value in a Map object, you can get the entire map object, you can also get the key collection or value collection of the Map object, you can get the value of the specified field, or you can perform the add and subtract operation on the integer value of the specified field. Redis can store object properties and property values, but memcached objects can only be converted to strings, if you want to modify the value of the object, you can only take the string out to convert to an object, then modify the object, and then converted to a string back to memcached, the cost is still very large, This is the advantage of Redis.
@Test Public voidTesthash () {//Test HashMapmap<string,string>m=NewHashmap<string,string>(); M.put ("Name", "Tom"); M.put ("Major", "Software"); M.put ("Age", "43"); Jedis.hmset ("M", M); List<String> name=jedis.hmget ("M", "name");//M is a key of key,name m and returns a listSystem.out.println (name); System.out.println ("Get Hash values=" +jedis.hvals ("M")); Iterator<String> It=jedis.hkeys ("M"). iterator (); while(It.hasnext ()) {String key=It.next (); SYSTEM.OUT.PRINTLN (Key+ ":" +jedis.hmget ("M", key)); } System.out.println ("Get Keys from Redis:" +jedis.hkeys ("M")); System.out.println ("Get Values from Redis:" +jedis.hvals ("M")); Map<string,string>map=jedis.hgetall ("M"); System.out.println ("Get map from Redis:" +map); //Test HashSetSYSTEM.OUT.PRINTLN ("---test hash set"); Jedis.hset ("S", "name", "Jack"); Jedis.hset ("S", "Age", "25"); System.out.println (Jedis.hexists ("S", "name")); System.out.println (Jedis.hget ("S", "name")); System.out.println (Jedis.hgetall ("S")); Map<string,string>smap=jedis.hgetall ("s"); System.out.println (SMAP); System.out.println (Jedis.hdel ("S", "name"));//clear the Name propertySystem.out.println (Jedis.hincrby ("s", "Age", 3)); System.out.println ("After incr:" +jedis.hgetall ("s")); }
3. Lists
List is a doubly linked list because Redis supports inserting and ejecting at both ends of the list, so the Redis list can be used as a queue or as a stack, in addition to a doubly linked list.
@Test Public voidtestlist () {System.out.println ("Test List"); Jedis.del ("Task"); Jedis.rpush ("Task", "do homework");//add at the end of the listJedis.rpush ("task", "Clean housr"); Jedis.lpush ("Task", "Rest");//Add in the list headerJedis.lpush ("task", "Watch TV"); System.out.println ("Length:" +jedis.llen ("task")); System.out.println ("Get all List:" +jedis.lrange ("task", 0,-1));//-1 means to the end, to take out data from start to finishSYSTEM.OUT.PRINTLN ("Target Index:" +jedis.lindex ("task", 2)); System.out.println (Jedis.lpop ("task"));//Remove Head DataSystem.out.println ("Get all List:" +jedis.lrange ("task", 0, 1)); System.out.println (Jedis.rpop ("task"));//Remove Tail DataSystem.out.println ("Get all List:" +jedis.lrange ("task", 0, 1)); }
4. Sets
The set of Redis is equivalent to Java HashSet, the elements are arranged in order, and the stronger is that it can easily find the sum, intersection and difference of two sets.
@Test Public voidTestset () {System.out.println ("Test Set"); Jedis.del ("S1"); Jedis.sadd ("S1", "4", "1", "3", "20");//OrderlySystem.out.println ("Get all S1:" +jedis.smembers ("S1"));//Order ofSystem.out.println ("Get no S1:" +jedis.scard ("S1")); Jedis.sadd ("S2", "4", "11", "13", "34", "3", "20"); System.out.println ("Get all S2:" +jedis.smembers ("S2"));//Order ofSystem.out.println ("Get no s2:" +jedis.scard ("S2")); System.out.println (Jedis.sinter ("S1", "S2"));//intersectionSystem.out.println (Jedis.sunion ("S1", "S2"));//and setSystem.out.println (Jedis.sdiff ("S1", "S2"));//Difference Set}
5. Sorted sets
Redis's sorted sets is a set supplement that can be sorted according to weights and also not allowed to be duplicated.
@Test Public voidTestsortedset () {System.out.println ("Testsortedset"); Jedis.zadd ("SS", A, "Tom");//The middle is the weighted value, sorted by weightJedis.zadd ("ss", 1, "Jack"); Jedis.zadd ("SS", "David"); Jedis.zadd ("SS", 3, "Jim"); System.out.println ("SortedSet Length:" +jedis.zcard ("ss"));//get the number of elementsSystem.out.println ("Sorted set:" +jedis.zrange ("SS", 0,-1));//output by weight valueJedis.zadd ("Ss1", 1, "Tom");//The middle is the weighted valueJedis.zadd ("Ss1", 3, "Jimmy"); Jedis.zadd ("Ss1", 2, "Alex"); Jedis.zadd ("SS1", 5, "Jim"); System.out.println ("SortedSet Length:" +jedis.zcard ("SS1"));//get the number of elementsSystem.out.println ("Sorted set:" +jedis.zrange ("Ss1", 0,-1));//output by weight valueSystem.out.println (Jedis.zscore ("Ss1", "Tom"));//get Tom's sort weights }
Third , Redis application
In conjunction with the above introduction to the REDIS data structure, Redis in the service side of the development technology, simply can be done cache, and can do data persistence, the following aspects are novice understanding.
1. Message Queuing
In the second part of this paper, the Redis has a doubly linked list list, and supports dual-input and double-out, so you can use Redis for Message Queuing, such as notification messages, tasks, messages, etc. can be stored in the message queue, and then the other end can be supported by the Redis most of the language consumption of data in the queue, This facilitates decoupling between the system modules, reduces the dependency between modules, and translates the synchronous message processing into asynchronous processing without causing the queue to block. Weibo's user Weibo list should be a cache made with Redis.
2. List the latest data for a listing
This can also be used in the Redis list to deal with, such as Weibo a large v of the number of comments, on the page must show only the latest dozens of comments, if there is a database, with the MySQL select Limit query data, all the data will be sorted, This is a very expensive opportunity, but if you use the Redis list you can use the Lrange ("key", 0,100) method so that you can take out the last 100 comments.
3. Counter
Because Weibo has the largest redis cluster, we still take Weibo for example, a star sent a theme "We" Weibo, like the number of millions of in two days, in this case, you can use Redis in the atomic subtraction operation, in Java, we know i++ or i--is not atomic, This means that it is not thread-safe, but there is no problem with Redis, you can use Jedis.hincrby ("weiboid", "likes", 1), which means that a tweet likes the number plus 1, which is thread safe.
4. Leaderboards, fetch top n data
Combined with the sorted Set introduced in the second part of this article, we can take out top n data, such as 100W users participating in the game, or 100W user Weibo, we want to take out the top 100 games, or the Hottest 100 tweets, The game results here or the microblog heat can be weights (score), operate in the cache, do not need to be sorted, can be quickly removed.
5. The discharge weight and the seek, the difference, the intersection
Redis uses set, as described in the second part of the Java program, when it is necessary to insert data into the set set, Redis will automatically do the redo, and can ask for a set of the same, intersection, and difference of set set in any two caches.
6. Pub/sub
Redis supports message publishing-subscription mode, which is ideal for chat message push.
Learning materials and references:
http://try.redis.io/has basic commands for Redis beginners to learn, and provides a command line interface.
Http://redis.io/topics/introduction Redis Basic Introduction
HTTP://WWW.CSDN.NET/ARTICLE/2013-10-07/2817107-THREE-GIANT-SHARE-REDIS-EXPERIENCE/1 Redis application at home and abroad
Http://www.cnblogs.com/whoamme/p/3532129.html Redis Basic Operations
http://www.360doc.com/content/15/0510/20/23016082_469494498.shtml Redis Applications
Novice See Redis (i)