Redis (ii) Advanced usage
Transactions
A Redis transaction is a collection of a set of commands. A transaction, like a command, is the smallest execution unit of Redis, and commands in one transaction are either executed or not executed.
You first need to multi the command to start the transaction and execute the transaction with the EXEC command.
127.0.0.1:6379>Multiok127.0.0.1:6379> Hset User:1name xiaomingqueued127.0.0.1:6379> Hset User:1name daxiongqueued127.0.0.1:6379>exec1) (integer)02) (integer)0127.0.0.1:6379> Hgetall User:11)"name"2)"Daxiong"3)"score"4)" A"
Multi represents the start of the transaction, returns OK for success, exec represents the execution of the transaction, returns the execution result of each command, and adds the command to execute in the middle of multi and exec. After the multi starts, all commands are not executed, but all are temporarily saved, and the commands are executed sequentially after the EXEC command is executed in the order in which they are saved. If there is a failure in the execution of the transaction (the execution of one command will continue after a failure), the developer will need to handle the consequences themselves. Note: Redis does not support rollback operations and causes REDIS error exceptions to be handled by developers. The Watchwatch command monitors the change of one or more key values, and once one of the keys is changed, the subsequent transaction is not executed and the monitoring continues until the EXEC command.
127.0.0.1:6379> Set Key1OK127.0.0.1:6379>Watch Keyok127.0.0.1:6379> Set Key2OK127.0.0.1:6379>Multiok127.0.0.1:6379> Set Key3QUEUED127.0.0.1:6379>exec (nil)127.0.0.1:6379>Get key"2"
Time-to-live (1) sets the timeout for key, which is automatically deleted to the key value after time-out, similar to the time-out in memcache.
expire key seconds//Set successfully returned 1, failed to return 0
127.0.0.1:6379>Set Session:aabb Uid1122ok127.0.0.1:6379> Expire Session:aabb -(integer)1127.0.0.1:6379>del session:aabb (integer)1127.0.0.1:6379> Expire Session:aabb -(integer)0 127.0.0.1:6379> Expire Session:aabb -(integer)1127.0.0.1:6379>ttl session:aabb (integer)290
(2) Query the remaining timeout time
TTL key
127.0. 0.1:63791127.0. 0.1:6379>290
(3) Cancel Time Out
127.0.0.1:6379>Get Session:aabb" -"127.0.0.1:6379>ttl session:aabb (integer)280127.0.0.1:6379>persist Session:aabb (integer)1127.0.0.1:6379>ttl session:aabb (integer)-1
(4) If you use the set-related command, the timeout for the key will be canceled
Cache DataIn some cases, the need to cache part of the site data, and the site data by the need for continuous updating (if it takes two hours to update), you can use Redis to cache this part of the data, set the data time-out of 2 hours, whenever there is a request to access the data in Redis first to find out whether there is , if there is a direct read, re-read the data from the database and load it into redis if it does not exist. When you cache data, you need to consider the size of the cached data, if the cache data is large, it will consume too much memory resources, it is necessary to limit the use of memory in the configuration file size (maxmemory). When the maxmemory limit is exceeded, Redis removes unwanted keys based on the policy specified by the Maxmemory-policy parameter, including the LRU algorithm.
SortThe sort command supports sorting of collection types, class table types, and ordered collection types.
127.0.0.1:6379> Lpush List1 2 6 3 4 9 8(integer)7127.0.0.1:6379>SortList1)"1"2)"2"3)"3"4)"4"5)"6"6)"8"7)"9"
You can sort the values of an ordered collection:
127.0.0.1:6379> Zadd Set - 2 + 3 - 1 - 5(integer)4127.0.0.1:6379>SortSet1)"1"2)"2"3)"3"4)"5"
The sort command can add desc to sort in reverse order
127.0. 0.1:6379sort Set desc1"5"2 "3"3"2"4"1 "
By parameter many times we need to sort by an attribute of the object corresponding to the ID, so how can we correlate multiple different data queries? (1) First, add three user IDs to the UserIDs
127.0. 0.1:63791233
(2) Second, add scores to three users respectively
127.0. 0.1:6379-OK127.0. 0.1:6379-OK127.0. 0.1:6379OK
(3) Finally, use the sort, by command to sort the user by default and the increment and decrement of fractions.
127.0.0.1:6379>SortUserIDs1)"1"2)"2"3)"3"127.0.0.1:6379>SortUserIDs by user_score_*1)"2"2)"1"3)"3"127.0.0.1:6379>SortUserIDs by user_score_*desc1)"3"2)"1"3)"2"
The get parameter get parameter does not affect sorting, it does so that the result returned by the sort command is no longer the value of the element itself, but rather the key value specified in the Get parameter, which supports the string type and the key of the hash type, as with the by parameter.
127.0.0.1:6379>SortUserIDs by user_score_* get user_name_*1)"xiaoming"2)"Daxiong"3)"Xiaohong"127.0.0.1:6379>SortUserIDs by user_score_* Desc get user_name_*1)"Xiaohong"2)"Daxiong"3)"xiaoming"
The store parameter store parameter is used for result saving. The sort command is one of the complex commands of Redis, and the use of poor performance bottlenecks. The time complexity of the sort command is O (N+mlog (m)), where n is the number of elements in the sorted list (set and ordered collection), and M is the number of elements returned. Redis creates a container of length n before sorting to store the elements to be sorted, although it is a temporary process, but sorting operations on multiple large data can seriously affect the performance of the system. Therefore, in the development of the need to note: (1) Minimize the number of elements in the sort key, reduce n (2) Use the limit parameter only to obtain the required data, reduce n (3) if the amount of data to be sorted is large, use the store name to cache the results whenever possible.
Task QueueTask queues are generally suitable for communication between producers and consumers, so it is easy to think of using list types to implement task queues in Redis, by creating a task queue, where the producer proactively lpush the data, and the consumer rpop the data to maintain a FIFO sequence. However, there is a problem, consumers need to take the initiative to request data, periodic requests will cause the waste of resources, so Redis provides a brpop command to solve the problem.
Brpop Key timeout
The Brpop command receives two parameters, the first parameter key is a key value, and the second parameter, timeout, is the time-out. When the Brpop command takes data, if the data is temporarily absent, the command blocks until the time-out is reached. If timeout is set to 0, it will wait indefinitely.
Priority QueueBased on task queue, how to implement priority queue? You can select multiple task queues, and the task priority for each task queue is different. Redis provides the following command, starting with the first key on the left to read and know that a data is returned.
Brpop key [key ...] timetout
Publish/Subscribe mode Redis provides a RABITMQ-like publish-subscribe model that publishes messages using the following command by the producer.
PUBLISH CHANNEL MESSAGE
The consumer subscribes to the message via the following message,
SUBSCRIBE CHANNEL MESSAGE
Producers:
#向channel. Test Publishing Messages 127.0. 0.1:6379>0 #返回0表明订阅者为0, no message 127.0published. 0.1:6379>1 #返回n表明订阅者为n, successfully released to 1 consumers
Consumers:
#订阅channel. Test message 127.0 . 0.1 : 6379 > subscribe Channel.test Reading messages ... (Press Ctrl -c to quit) 1 ) " subscribe " 2 ) channel.test " 3 " (integer) 1
message #接收到来自channel. Test 1 " message " 2 " channel.test " 3 " Hello "
PipingThe underlying communication protocol for Redis provides support for pipelines. A pipeline can send multiple commands at once and return the results once after execution, and the set of commands can be piped together when each command in a set of commands does not depend on the result of the previous command. Pipelines reduce the cumulative value of the round-trip experiment by reducing the number of client-to-Redis communications.
Space Saving(1) Compact key name and key value (2) Redis provides two internal encodings for each data type. For example, the hash type of storage is implemented by a hash table, Redis chooses the encoding type based on how much data is available, and when the data is small, it uses a compact but poorly performing internal encoding, and the data changes to a hash list.
Redis (ii) Advanced usage