[Stick to the top] redis installation, class library, and demo

Source: Internet
Author: User
Tags key string redis version
1. Install redis a. System Environment and description Ubuntu is used for the Linux operating system, and the latest stable version 2.8.9 is selected for the Redis version. The client selects the Java connector jedisb.installer of redis. wgetdownload.redis.ioreleasesredis-2.8.9.tar.gz c. in the directory, decompress the package

1. Install redis a. System Environment and description Ubuntu is used for the Linux operating system, and the latest stable version 2.8.9 is selected for the Redis version. The client selects the Redis Java version jedis B. Installation Steps wgethttp: // download. redis. io/releases/redis-2.8.9.tar.gz c. in the directory, decompress according to the package

I. redis Installation

A. System Environment and description

The Linux operating system uses Ubuntu, And the Redis version selects the latest stable version 2.8.9. The client selects the Redis Java version jedis.

B. Installation Steps

Wgethttp: // download. redis. io/releases/redis-2.8.9.tar.gz

C. In the directory, extract according to the package, generate a new directory redis-2.8.9

Tar xvfz redis-2.8.9.tar.gz

D. Enter the decompressed directory and compile it.

Cd redis-2.8.9

Sudo make

NOTE: If there are no obvious errors, the compilation is successful.

Check whether gcc is installed before compilation. If command not found is reported, solve: sudo apt_get install make gcc

E. Install

Sudo make install

Note: Generally, in Ubuntu, sudo must be used to enhance permissions.

F. After the installation is successful, run the test to check whether the Redis function is normal.

Sudo make test

G. Start the Redis Service

Find the directory where Redis is installed: find/-name 'redis * '------ find the file whose name contains redis in the root directory

After searching, we found that Redis was installed in the/usr/local/bin/directory.

Next, start the Redis service:

/Usr/local/bin/redis-server

H. view the Redis Process

Ps-ef | grep redis

Ii. redis class library

1. keys
Redis is essentially a key-value db, so let's first look at its key. First, the key is also a string type, but the key cannot contain boundary characters.
Keys that contain spaces and line breaks are not allowed because they are not binary safe strings.
By the way, redis does not limit the use of binary characters, which is restricted by the redis protocol. "\ R \ n" is a special character in the Protocol format.
Some commands in redis 1.2 and later protocols have begun to use the new protocol format (such as MSET ). At present, we should regard boundary characters as invalid keys,
Avoid being entangled by bugs.
In addition, object-type: id: field is an introduction to a key Format Convention. For example, user: 1000: password, blog: xxidxx: title
The length of the key should not be too long. The reason is that the memory usage is obvious, and the query time is relatively short and the key usage is slower. However, too short keys are also recommended,
Such as u: 1000: pwd. Obviously, the above user: 1000: password is not readable.
The following describes key-related commands.
Exits key to test whether the specified key exists. If the return value is 1, the specified key exists, and the return value is 0.
Del key1 key2... keyN deletes a given key and returns the number of deleted keys. 0 indicates that none of the given keys exist.
Type key returns the value type of the given key. If the return value is none, the key does not exist. The string character type. The list linked list type is set unordered...
Keys pattern returns all keys matching the specified mode. The following is an example.
Randomkey returns a random key selected from the current database. If the current database is empty, an empty string is returned.
Rename the oldkey newkey atom to rename a key. If newkey exists, it will be overwritten. If 1 is returned, it indicates success and 0 fails. It may be that the oldkey does not exist or is the same as the newkey.
Renamenx oldkey newkey is the same as above, but if newkey exists, return failure
Dbsize returns the number of keys of the current database.
Expire key seconds specifies the expiration time for the key, in seconds. 1 is returned successfully. 0 indicates that the key has been set to expire or does not exist.
Ttl key returns the remaining expiration seconds of the key with the specified expiration time.-1 indicates that the key does not exist or the expiration time has not been set.
Select db-index: select the database through the index. The default number of connected databases is 0, and the default number of databases is 16. 1 indicates success, 0 indicates failure
Move key db-index: move the key from the current database to the specified database. 1 is returned. 0 if the key does not exist or it is already in the specified database
Flushdb deletes all keys in the current database. This method will not fail. Use with caution
Flushall deletes all keys in all databases. This method will not fail. More cautious
2. string type
String is the most basic type of redis, and the string type is binary secure. It means that the redis string can contain any data. For example, JPG images or serialized objects
. From the internal implementation, the string can be viewed as a byte array, and the maximum value is 1 GB. The following is the definition of the string type.

Struct sdshdr {
Long len;
Long free;
Char buf [];
};

Buf is a char array used to store the actual string content. In fact, byte in char and c # is equivalent to one byte.
Len is the length of the buf array, and free is the number of available bytes in the array. We can understand why the string type is binary secure. Because it is essentially a byte array.
Of course, it can contain any data. In addition, some commands of the string type can be processed by int, such as incr. The following describes in detail. Other types of apsaradb for redis include list, set, sorted set, and hash.
They can only contain the string type.
If only the string type is used, redis can be regarded as memcached with the persistence feature. Of course, redis has many more operations on the string type than memcached. As follows:
Set key value: set the value corresponding to the key to the string type value. If the return value is 1, the operation is successful, and the return value is 0.
The setnx key value is the same as the preceding one. If the key already exists, 0 is returned. Nx means not exist
Get key obtains the string value corresponding to the key. If the key does not exist, nil is returned.
Getset key value atomic set key value, and return the old value of the key. If the key does not exist, nil is returned.
Mget key1 key2... keyN obtains the values of multiple keys at a time. If the corresponding key does not exist, nil is returned. The following is an experiment. First, clear the current database, and then
When k1 and k2are set, corresponding nil is returned for k3.

Redis> flushdb
OK
Redis> dbsize
(Integer) 0
Redis> set k1
OK
Redis> set k2 B
OK
Redis> mget k1 k2 k3
1. ""
2. "B"
3. (nil)

Mset key1 value1... keyN valueN multiple key values are set at a time. Success returns 1, indicating that all values are set. Failure Returns 0, indicating that no value is set.
Msetnx key1 value1... keyN valueN is the same as above, but the existing key is not overwritten.
Incr key adds the key value and returns a new value. Note that if incr is not an int value, an error is returned. If incr is a non-existent key, the key is set to 1.
The decr key is the same as the key, but the subtraction operation is performed. If a decr key does not exist, the key is set to-1.
Incrby key integer is the same as incr, and a specified value is added. If the key does not exist, the key is set and the original value is 0.
Decrby key integer is the same as decr, and the specified value is subtracted. Decrby is completely for readability. We can use a negative value of incrby to achieve the same effect, and vice versa.

Substr returns the string value of the truncated key. Note that the key value is not modified. The subscript starts from 0. (redis Versions later than 2.0 do not include 2.0. The getrange parameter is the same .)
Append key value appends value to the string value of the specified key, and returns the length of the new string value. The following is an example.

Redis> set k hello
OK
Redis> append k, world
(Integer) 11
Redis> get k
"Hello, world"
Substr key start end
Redis> substr k 0 8
"Hello, wor"
Redis> get k
"Hello, world"

3. list

The list type of redis is actually a two-way linked list of the string type for each sub-element. Therefore, the algorithm time complexity of the [lr] push and [lr] pop commands is O (1)
In addition, the list records the length of the linked list. Therefore, the llen operation is O (1). the maximum length of the linked list is (32 power-1 of 2 ). We can use the push and pop operations to extract the head of the linked list
Or add the deletion element at the end. This allows the list to be used as both a stack and a queue. It is interesting that the pop operation of list also has a blocking version. When we [lr] pop
The list object is. If the list object is empty or does not exist, nil is returned immediately. However, B [lr] pop of the blocked version can be blocked. Of course, a timeout value can be added, and nil will be returned after the timeout.
. Why is pop blocked? It is mainly used to avoid polling. A simple example is to use list to implement a work queue. The thread that executes the task can call the pop of the blocked version.
In this way, you can avoid polling to check whether a task exists. When a task comes, the worker thread can return immediately or avoid the delay caused by polling. OK. The following describes the list-related commands.
Lpush key string adds a string element to the header of the list corresponding to the key. If the return value is 1, the result is successful. If the return value is 0, the key exists and is not of the list type.
Rpush key string is the same as above. Add it at the end
Llen key returns the length of the list corresponding to the key. If the key does not exist, 0 is returned. If the key type is not list, an error is returned.
Lrange key start end: returns the elements in the specified range. The subscript starts from 0, and the negative value indicates calculation from the end.-1 indicates the last element. If the key does not exist, an empty list is returned.
Ltrim key start end intercepts the list and retains the elements in the specified range. 1 is returned successfully. If the key does not exist, an error is returned.
When the lset key index value is set to the element value specified in the list, 1 is returned successfully. If the key or subscript does not exist, an error is returned.
The lrem key count value deletes the same count and value elements from the list corresponding to the key. Delete all when count is 0
The lpop key deletes the element from the list header and returns the deletion element. If the list corresponding to the key does not exist or is null, nil is returned. If the corresponding value of the key is not a list, an error is returned.
Rpop is the same as above, but deleted from the end
Blpop key1. .. keyN timeout from left to right scan and return lpop for the first non-empty list and return, such as blpop list1 list2 list3 0. If the list does not exist
If list2 and list3 are both non-empty, lpop is performed on list2 and elements deleted from list2. If all lists are empty or do not exist, the timeout seconds are blocked. If the value of timeout is 0, the system is blocked all the time.
If a client pushes any key in key1. .. keyN when blocking, the client that is first blocked on this key will return immediately. If timeout occurs, nil is returned. A bit like select or poll in unix
Brpop is the same as blpop. One is to delete from the header and the other is to delete from the tail.
Rpoplpush srckey destkey removes elements from the end of the srckey list and adds them to the header of the list corresponding to the destkey. Finally, the removed element value is returned. The entire operation is atomic. If the srckey is empty
Or nil does not exist.
4. set
Redis's set is a unordered set of the string type. The set element can contain a maximum of (32 to the power of 2-1) elements. Set is implemented through hashtable, so the complexity of adding, deleting, and searching is O (1 ). Hashtable automatically adjusts the size as it is added or deleted. Note that synchronization (get write lock) is required when the hash table size is adjusted to block other read/write operations. It may soon be implemented using the skip table (skip list ).
The table has been used in sorted set. In addition to basic addition and deletion operations, other useful operations also include union and intersection of sets ),
Difference ). Through these operations, you can easily implement the friend recommendation and blog tag FUNCTIONS In sns. The following describes the set commands in detail.
Sadd key member adds a string element to the set corresponding to the key. 1 is returned successfully. If the element and 0 are returned in the set, an error is returned if the set corresponding to the key does not exist.
Srem key member removes the given element from the set corresponding to the key. If member does not exist in the set or the key does not exist, 0 is returned. If the key does not belong to the set type, an error is returned.
The spop key is deleted and a random element in the set corresponding to the key is returned. If the set is null or the key does not exist, the nil is returned.
Srandmember key is the same as spop. An element in the set is randomly selected, but the element is not deleted.
Smove srckey dstkey member removes the member from the srckey's corresponding set and adds it to the dstkey's corresponding set. The entire operation is atomic. If member does not exist in srckey, 0 is returned. If
An error is returned when the key is not of the set type.
Scard key returns the number of set elements. If set is null or the key does not exist, 0 is returned.
Sismember key member determines whether the member is in the set. If yes, 1 or 0 is returned, indicating that the member does not exist or the key does not exist.
Sinter key1 key2. .. keyN returns the intersection of all given keys
Sinterstore dstkey key1. .. keyN is the same as sinter, but the intersection is saved under dstkey at the same time.
Sunion key1 key2. .. keyN returns the union of all given keys
Sunionstore dstkey key1. .. keyN is the same as sunion, and the Union is saved under dstkey.
Sdiff key1 key2. .. keyN returns the difference set of all given keys
Sdiffstore dstkey key1. .. keyN is the same as sdiff, and the difference set is saved under dstkey.
Smembers key returns all elements of the set corresponding to the key, and the result is unordered.
5 sorted set
Similar to set, sorted set is also a set of string elements. The difference is that each element is associated with a score of the double type. The implementation of sorted set is a mixture of skiplist and hash table.
When an element is added to a set, the score ing from an element to score is added to hashtable. Therefore, the overhead for getting score from an element is O (1 ), the ing from another score to the element is added to the skip list.
And sorted by score, so we can get the elements in the Set in sequence. The overhead of adding and deleting operations is the same as that of O (log (N) and skip list. redis's skip list uses a two-way linked list.
You can retrieve elements from the end in reverse order. Sorted set is most frequently used as an index. We can store the fields to be sorted as scores, and the Object id is stored as an element. The following are the commands related to sorted set:
Zadd key score: add an element to the set in member. If an element exists in the Set, the corresponding score is updated.
Zrem key member deletes the specified element. 1 indicates that the operation is successful. If the element does not exist, 0 is returned.
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 ranking (subscript) of the specified Element in the set. The elements in the set are sorted by score in ascending order.
Zrevrank key member is the same as above, but the elements in the set are sorted by score in ascending order.
The zrange key start end operation is similar to the lrange operation to specify the range elements from the collection. The returned result is an ordered result.
Zrevrange key start end is the same as above. The returned results are in reverse order of score.
Zrangebyscore key min max returns the element of the score in the specified range in the collection.
Zcount key min max returns the number of scores in the specified range in the set.
Zcard key returns the number of elements in the set.
The zscore key element returns the score corresponding to the given element.
Zremrangebyrank key min max deletes the elements in the specified range in the collection.
Zremrangebyscore key min max deletes the element of the score in the specified range in the set.
6. hash
Redis hash is a string-type field and value ing table. It is added, and the delete operation is O (1) (average). hash is particularly suitable for storing objects. Compared to saving each field of an object
Single string type. Storing an object in the hash type consumes less memory and makes it easier to access the entire object. Memory saving is because zipmap (also known as small hash) is used to store a new hash object. This zipmap is not actually a hash table, but zipmap can save a lot of metadata storage overhead for hash compared to normal hash implementation. Although zipmap's addition, deletion, and search operations are all O (n), the number of fields of general objects is not large. Therefore, the use of zipmap is also very fast, that is to say, the average addition and deletion is still O (1 ). If the size of field or value exceeds a certain limit, redis will automatically replace zipmap with a normal hash internally. This limit can be specified in the configuration file.

Redis> set test dsf
OK
Redis> set tast dsaf
OK
Redis> set tist adff
OK
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 # configure up to 64 Fields
Hash-max-zipmap-value 512 # set the maximum value to 512 bytes.
The following describes hash commands.
Hset key field value: Set hash field to the specified value. If the key does not exist, create
Hget key field to get the specified hash field
Hmet key filed1. .. fieldN get all the specified hash filed
Hmset key filed1 value1... filedN valueN simultaneously sets multiple hash Fields
Hincrby key field integer adds the specified hash filed Value
Hexists key field test whether the specified field exists
Hdel key field deletes the specified hash field
Hlen key returns the number of specified hash Fields
Hkeys key returns all fields in the hash
Hvals key returns all hash values
Hgetall returns all the filed and value of the hash.

Iii. demo

Preparations: Introduce the redis package

String

List

Set

Map

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.