Redis Learning Redis installation, class library and demo

Source: Internet
Author: User
Tags key string set set

First, Redis the installation

A. System Environment and description

The Linux operating system chooses Ubuntu, and the Redis version chooses the latest stable version of 2.8.9. The client chooses the Java version of Redis Jedis

B. Installation steps


c. under the directory, unzip the package to generate a new directory redis-2.8.9

Tar Xvfz redis-2.8.9.tar.gz

d. Enter the directory after decompression to compile

CD redis-2.8.9

sudo make

Description: If there is no obvious error, the compilation succeeds

Before compiling, please check if gccis installed, if command not found, fix:sudo apt_get install make gcc

E. installation

sudo make install

Note: In general, in the Ubuntu system, you need to use sudo to elevate permissions

F. after the installation is successful, you can run the test to verify that Redis is functioning properly

sudo make test

G. starting the Redis service

Find the directory for redis installation: Find /-name ' redis* '------ look for files with Redis in the root directory

After searching, Redis was found to be installed in the /usr/local/bin/ directory.

Next, start the Redis service:


H. viewing the Redis process

Ps-ef | grep Redis

Second, Redis the class library

1. Keys
Redisessentially a key-value db, so let's take a look at his key first. Key is also a string type, but cannot include boundary characters in key
Because key is not a binary safe string, keys such as "My Key" and "mykey\n" that contain spaces and line breaks are not allowed
By the way, the use of binary characters is not restricted within Redis, which is limited by the Redis protocol. "\ r \ n" is used as a special character in the protocol format.
Some of the commands in the Redis 1.2 protocol have begun to use the new protocol format (such as Mset). In short, the inclusion of boundary characters as illegal key bar,
Avoid being entangled by bugs.
In addition to the introduction of a format convention for key, Object-type:id:field. Like User:1000:password,blog:xxidxx:title.
And the length of the key is best not too long. The reason is obviously the memory ah, and the lookup time relatively short key is also slower. But I also recommend a short key,
Like U:1000:pwd, that kind of. Obviously, the above user:1000:password is very readable.
The following key-related commands are described below
Exits key test Specifies whether key exists, returns 1 for presence, 0 does not exist
Del key1 key2 .... KeyN deletes the given key, returns the number of deleted keys, 0 means the given key does not exist
Type key returns the value type of the given key. The return none indicates that there is no key,string character type, the list linked list type set unordered collection type ...
The keys pattern returns all keys that match the specified pattern, given an example
Randomkey returns a randomly selected key from the current database and returns an empty string if the current database is empty
Rename Oldkey Newkey The atom is renamed a key, if newkey exists, it will be overwritten, return 1 indicates success, 0 fails. Maybe Oldkey doesn't exist, or it's the same as Newkey.
Renamenx Oldkey Newkey Ibid, but if Newkey exists return failure
Dbsize returns the number of keys for the current database
Expire key seconds Specifies the expiration time, in seconds, for the key. Returns 1 success, 0 indicates that key has been set to expire or does not exist
TTL key returns the remaining expiration seconds of a key that has set an expiration time-1 indicates that key does not exist or has not been set to expire
Select Db-index selects the database by index, the default connection database is all 0, and the default number of databases is 16. Returns 1 indicates success, 0 failed
Move key Db-index moves the key from the current database to the specified database. Returns 1 success. 0 if key does not exist or is already in the specified database
FLUSHDB Delete all keys in the current database, this method does not fail. Use with caution
Flushall all keys in all databases are deleted, this method does not fail. More cautious use
2. String Type
The string is the most basic type of Redis, and the string type is binary safe. This means that a Redis string can contain any data. For example, JPG images or serialized objects
。 From an internal implementation, a string can be treated as a byte array with a maximum limit of 1G bytes. The following is the definition of a string type.

struct SDSHDR {
Long Len;
Long free;
Char buf[];

buf is a char The array is used to store the actual string contents. In fact, char is equivalent to Byte in C #, which is a byte
Len is the length of the BUF array, and free is the number of available bytes remaining in the array. This makes it possible to understand why the string type is binary safe. Because it's essentially a byte array. The
can of course contain any data. In addition, the string type can be processed by a partial command by Int. For example, INCR commands, detailed below. There are other types of redis like list,set,sorted set, hash
they contain both elements and can only be of type string.
If only a string type is used, Redis can be seen as a memcached with persistence. Of course, Redis has a lot more to do with string types than memcached. As follows:
Set key value sets key corresponding to value of string type, return 1 for success, 0 failure
Setnx key value Ibid, if key already exists, returns 0. NX is the meaning of not exist
get key gets the string value corresponding to key, if key does not exist return nil
Getset key value of the atomic setting key, and returns the old value of key. If key does not exist return nil
Mget key1 key2 ... keyN gets the value of more than one key at a time, and returns nil if the corresponding key does not exist. Here's an experiment, first emptying the current database, and then
setting K1,K2. K3 returns nil when retrieved

Redis> Flushdb
Redis> dbsize
(integer) 0
Redis> set K1 A
Redis> Set K2 b
redis> mget K1 K2 K3
1. "A"
2. "B"
3. (nil)

mset key1 value1 ... keyN valuen Setting the value of multiple keys at once , successfully returning 1 means that all values are set, and a failure return of 0 means that no value is set
Msetnx key1 value1 ... KeyN Valuen Ibid, but does not overwrite existing key
INCR Key does a Gaga operation on the value of key and returns the new value. Note INCR A value that is not an int returns an error incr a nonexistent key, setting key to 1
Decr key Ibid, but do is reduce the operation, DECR one does not exist key, then set key to 1
Incrby key integer with INCR, plus the specified value, key does not exist when the key is set, and that the original value is 0
Decrby key integer with DECR, minus the specified value. Decrby is purely for readability, we can achieve the same effect by Incrby a negative value, and vice versa.

substr Returns the string value of the truncated key , noting that the value of key is not modified. The subscript is starting from 0. (Redis does not include 2.0 after version 2.0, and the method used is the same as the GetRange parameter.) )
Append key value appends value to the string value of the specified key, returning the length of the new string value. Here's an example.

Redis> Set K Hello
Redis> Append K, world
(integer) 11
Redis> Get K
SUBSTR Key Start end
Redis> substr K 0 8
Redis> Get K

3. List

Redisthe listThe type is actually a doubly linked list where each child element is a string type. So [Lr]push and [Lr]pop] the algorithm time complexity of the command is O (1)
The list will also record the length of the linked list. Therefore the Llen operation is also O (1). The maximum length of a linked list is (2 of 32 square-1). We can manipulate the head from the list by Push,pop
or trailing add delete element. This allows the list to be used as either a stack or as a queue. The interesting thing is that the pop operation of the list is also blocked version. When we [Lr]pop a
The list object is if the list is empty, or does not exist, it returns nil immediately. However, the blocked version of the B[lr]pop can be blocked, of course, can be added to the timeout period, after the timeout will also return nil
。 Why block versions of Pop, primarily to avoid polling. As a simple example, if we use list to implement a Task Force column. The thread that performs the task can call a blocked version of Pop to
Get a task this avoids polling to check for the presence of a task. The worker thread can return immediately when the task comes, or it can avoid the delay caused by polling. OK the list related commands are described below
Lpush key string adds a string element to the header of the key corresponding to the list, returns 1 for success, 0 indicates that key exists and is not a list type
Rpush key string Ibid, added at tail
Llen Key returns the length of the list, key does not exist return 0, if the key corresponding type is not a list return error
Lrange Key start end returns the element within the specified interval, the subscript starts at 0, the negative value is calculated from the back, 1 is the last element of the countdown, and key does not exist. Returns an empty list
LTrim key start end intercepts list, retains elements within specified interval, returns 1,key without return error
LSet Key index value sets the value of the element specified in the list, returns 1,key successfully, or the subscript does not have a return error
Lrem Key count value removes the same element as count and value from the key corresponding list. Count is 0 when you delete all
Lpop key removes the element from the head of the list and returns the deleted element. If key corresponds to list does not exist or is null returns NIL if key corresponding value is not list returned error
Rpop Ibid, but removed from the tail
Blpop Key1...keyn Timeout left-to-right scan returns a LPOP operation on the first non-empty list and returns, such as Blpop List1 list2 list3 0, if list does not exist
LIST2,LIST3 are non-null and do Lpop to list2 and return elements removed from List2. If all the lists are empty or nonexistent, the timeout second is blocked, and a timeout of 0 means that it is blocked.
When blocking, if a client has a push operation on any key in Key1...keyn, the first client that is blocked on that key will return immediately. If the timeout occurs, nil is returned. Sort of like a Unix select or poll.
Brpop with Blpop, one is removed from the head and one is removed from the tail
Rpoplpush Srckey Destkey Removes the element from the tail of the srckey corresponding list and adds it to the head of the destkey corresponding to the list, and finally returns the value of the removed element, the entire operation being atomic. If Srckey is empty
Or there is no return nil
4. Set
Redis's set is an unordered collection of type string. The set element can contain a maximum of (2 of 32 square-1) elements. Set is implemented through Hashtable, so the complexity of adding, deleting, and finding is O (1). The Hashtable automatically resizes as you add or remove them. It is important to note that when adjusting the hash table size, synchronization (acquisition of write locks) is required to block other read and write operations. It may be possible to use the Skip list for
The jump table has already been used in the sorted set. For the Set collection type in addition to the basic add-delete operation, other useful operations include the collection Union, the intersection (intersection),
Subtraction (difference). Through these actions can easily realize the SNS in the Friend referral and blog tag function. Set-related commands are detailed below
Sadd Key member adds a string element to the set set that corresponds to key, successfully returns 1 if the element and the corresponding set returned in the collection 0,key no return error
Srem Key member removes the given element from the key corresponding set, returns 1 successfully, if the member does not exist in the collection or the key does not exist return 0, if the key corresponding to a value other than the set type returns an error
Spop key deletes and returns the key corresponding to a random element in set, if set is empty or key does not exist return nil
Srandmember key with Spop, randomly takes an element in set, but does not delete the element
Smove Srckey Dstkey member remove Srckey from the member corresponding set and add it to the dstkey corresponding set, the entire operation is atomic. A successful return of 1 if member does not exist in Srckey returns 0 if
Key is not a set type return error
SCard Key returns the number of elements of set, if set is empty or key does not exist return 0
Sismember Key member determines whether the member is in set, there is a return 1,0 that does not exist or key does not exist
Sinter key1 Key2...keyn Returns the intersection of all given keys
Sinterstore Dstkey Key1...keyn with Sinter, but will also save the intersection to Dstkey
Sunion key1 Key2...keyn Returns the set of all the given keys
Sunionstore Dstkey Key1...keyn with Sunion, and simultaneously save and set to Dstkey
Sdiff key1 Key2...keyn Returns the difference set for all given keys
Sdiffstore Dstkey Key1...keyn with Sdiff, and simultaneously save the difference set to Dstkey under
Smembers key returns all elements of the set corresponding to the key, the result is unordered
5 sorted Set
As with set sorted set is also a collection of elements of type string, but each element is associated with a double type of score. The implementation of sorted set is a mixture of skiplist and hash table
When an element is added to the collection, an element-to-score mapping is added to the Hashtable, so the cost of getting score for a given element is O (1), and another score-to-element mapping is added to the Skip list
and sort by score, so you can get the elements in the collection in order. Add, the delete operation cost is the same as the cost of O (log (N)) and skip list, and the Redis skip list implementation uses a doubly linked list, so
You can take an element from the tail in reverse order. The most common use of sorted set is to use it as an index. We can store the fields to be sorted as score, the object's ID when the element is stored. Here is the sorted set related command
Zadd key score member adds elements to the collection, the element exists in the collection and updates the corresponding score
Zrem Key member Delete the specified element, 1 indicates success, if the element does not exist return 0
Zincrby Key INCR member increases the score value of the corresponding member, then moves the element and keeps the skip list in order. Returns the updated score value
Zrank Key member returns the rank (subscript) of the specified element in the collection, and the elements in the collection are sorted by score from small to large
Zrevrank Key member Ibid, but the elements in the collection are sorted by score from large to small
Zrange key start end resembles the lrange operation to specify the element of the interval from the collection. Returns an ordered result
Zrevrange key Start end Ibid, return result is in reverse order of score
Zrangebyscore Key min Max returns the elements of score in a given interval in the collection
Zcount Key min Max returns the number of score at a given interval in the collection
Zcard Key returns the number of elements in the collection
Zscore key element returns the score corresponding to the given element
Zremrangebyrank key min Max deletes elements in the collection that rank in a given interval
Zremrangebyscore key min Max deletes elements from the collection score at a given interval
6. Hash
Redis Hash is a string-type field and value mapping table. It is added, and the delete operation is O (1) (average). Hash is ideal for storing objects. Chengkun each word of an object
A single string type. Storing an object in a hash type consumes less memory and makes it easier to access the entire object. The reason for saving memory is that when a new hash object is created, it is stored with Zipmap (also known as small hash). This zipmap is not actually hash table, but zipmap compared to the normal hash implementation can save a lot of the hash itself needs some metadata storage overhead. Although Zipmap's additions, deletions, and lookups are all O (n), there are not too many field numbers for general objects. So the use of Zipmap is also very fast, that is, add delete average or O (1). If the size of field or value exceeds a certain limit, Redis automatically replaces the zipmap with the normal hash implementation internally. This restriction can be specified in the configuration file

redis> set test DSF
Redis> set tast dsaf
Redis> set tist adff
Redis> keys t*
1. "Tist"
2. "Tast"
3. "Test"
Redis> keys t[ia]st
1. "Tist"
2. "Tast"
Redis> keys t?st
1. "Tist"
2. "Tast"
3. "Test"

Hash-max-zipmap-entries64 # configuration fields up to a maximum of
Hash-max-zipmap-value #配置value最大为512字节
The following describes the hash-related commands
Hset key field value sets the hash field to the specified value, and if key does not exist, first create
Hget key field gets the specified hash field
Hmget key FILED1....FIELDN Get all the specified hash filed
Hmset key filed1 value1 ... filedn valuen multiple field with hash set
Hincrby key field integer adds the specified hash filed plus the given value
Hexists key Field test Specifies whether the field exists
Hdel key field deletes the specified hash field
Hlen Key returns the number of field in the specified hash
Hkeys Key returns all field of hash
Hvals key returns all value of hash
Hgetall returns all filed and value of hash

Third, Demo

preparatory work: Introduction Redis Package





Redis Learning Redis installation, class library and demo

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: 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.