Redis (ii) Advanced usage

Source: Internet
Author: User

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:1 name xiaomingqueued127.0.0.1:6379> hset user:1 Name daxiongqueued127.0.0.1:6379> exec1) (integer) (integer) 0127.0.0.1:6379> hgetall user:11) "name" 2) "Daxiong" 3 ) "Score" 4) "61"
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 key 1ok127.0.0.1:6379> watch keyok127.0.0.1:6379> set key 2ok127.0.0.1:6379> Multiok127.0.0.1:6379> set key 3queued127.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:6379> expire Session:aabb (integer) 1127.0.0.1:6379> ttl session:aabb (integer) 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 List 1 2 6 3 4 9 8 (integer) 7127.0.0.1:6379> sort list1) "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> sort Set1) "1" 2) "2" 3) "3" 4) "5"
The sort command can add desc to sort in reverse order
127.0.0.1:6379> sort 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:6379> Lpush UserIDs 1 2 3 (integer) 3
(2) Second, add scores to three users respectively
127.0.0.1:6379> set User_score_1 50ok127.0.0.1:6379> set user_score_2 30ok127.0.0.1:6379> set User_score_3 70OK
(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> sort userids1) "1" 2) "2" 3) "3" 127.0.0.1:6379> sort UserIDs by User_score_*1) "2" 2) "1" 3) "3" 127.0.0. 1:6379> sort UserIDs 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> sort UserIDs by user_score_* get user_name_*1) "Xiaoming" 2) "Daxiong" 3) "Xiaohong" 127.0.0.1:6379> Sort UserIDs 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 Publish message 127.0.0.1:6379> publish Channel.test Hello (integer) 0 #返回0表明订阅者为0, no message is published 127.0.0.1:6379> Publish Channel.test Hello (integer) 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
#接收到来自channel. Test message 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

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.