NoSQL's in-depth redis

Source: Internet
Author: User
Tags redis server

Before we introduced a brief introduction to Redis, knowing some of its features and its role, let's look at some of the simple commands it uses in practice, and some of its advanced features.

One, Common command 1, String type
(1)Set Key valueNX: IfKeyDoes not exist then establishes XX: ifKeyexists, its value is modified (2)Get Key: Take Value (3) Mset key1 value1 Key2 value2 set multiple values at once (4) Mget key1 Key2: Get multiple values at once (5) GetRangeKey StartStop: Gets the string in the [StartThe value of the stop] range for the subscript of the string, the left number from the0Start, right number from-1Start Note: whenStart>length, the empty string is returned when Stop>=length is truncated to the end of the string ifStartThe position is at the right of stop, and an empty string is returned (6) GetsetKeyNrevalue: Gets and returns the old value, setting the new value (7) incrKey: Self-increment, returns the new value if incr one is notintOfvalueThe error is returned, incr a non-existentKey, you setKeyFor1(8) IncrbyKey 2: Jump2Self-increment (9) strlenKey: Takes the specifiedKeyOfvalueThe length of the value (Ten) SetexKey  Time value: SetKeyThe corresponding valuevalue, and set the validity period to TimeSeconds
2. List Type
(1) Lpush key value: Inserts the value into the list header (2) Rpush key value: Inserts the value into the end of the list (3) Lpop key: Returns and deletes the list header element (4) Rpop key: Returns and deletes the linked list trailing element (5) Lrange keyStartStop: Returns the list in the list [Start, the element in Stop] (6) LremKey Count value: Remove from linked listvalueValue, deletingCountThe absolute value of avalueAfter the endCount>0Remove from table headerCount<0Delete from end of tableCount=0Delete all (7) LTrimKey StartStop: CutKeyThe corresponding link, cut [Start, stop] a paragraph and re-assign the restructuring toKey(8) lindexKeyIndex: Returns the value on the index (9) LlenKey: Calculates the number of elements in a linked list (Ten) LinsertKey  After|beforeSearchvalue: InKeySearch in the list and insert before the search value |value( One) Rpoplpush source dest: Take out the end of source, put it on the Dest head, and return the cell value

3. Hash type

(1) Hset myhash Field value: Sets the field for Myhash as value (2) hsetnx myhash field value: Does not exist when you set the Myhash field to value (3) Hmset myhash field1 value1 field2 value2: Set multiple field (4) hget myhash field: Gets the specifiedHashField5) Hmget Myhash field1 field2: Get more than one field at a time (6) Hincrby myhash Field5: The specifiedHashfield plus the given value (7) hexists Myhash Field: Tests whether the specified field exists (8) Hlen Myhash: BackHashThe number of field (9) Hdel myhash field: Deletes the specified field (Ten) Hkeys Myhash: BackHashAll the field ( One) Hvals Myhash: BackHashAll the value ( A) Hgetall Myhash: Gets aHashAll field and value in

4. Set type

(1) SaddKeyValue1 value2: Add elements to the collection (2) smembersKey: Gets all the elements of the collection (3) SremKeyValue: Deletes an element of the collection (4) SpopKey: Returns and Deletes the collection1A random element (which can be drawn in a lottery and not repeatedly pumped to someone) (5) SrandmemberKey: Randomly take an element (6) SismemberKeyValue: Determines whether the collection has a value (7) SCardKey: Returns the number of collection elements (8) Smove Source Dest Value: Moves the value of source to the Dest collection (9) sinter Key1 Key2 Key3: The intersection of Key1 Key2 Key3 (Ten) sunion Key1 Key2: The set of Key1 Key2 ( One) Sdiff Key1 Key2: The difference set of Key1 Key2 ( A) Sinterstore Res key1 Key2: Find the intersection of Key1 Key2 and exist in res

5. Zset Type

(1) Zadd key score1 value1: add Element (2) Zrange keyStartStop [Withscore]: After sorting the set, return to rank [Start, the element of stop] is the ascending continuation arrangement by default Withscores is the score also prints out (3) ZrankKeyMember: Ranking of query member (ascending0First name) (4) ZrangebyscoreKey min MaxThe [Withscores] collection (ascending) sorts and takes score in the [min,Max] within the element (5) ZrevrankKeyMember: Query member rank (descending0First name) (6) ZremrangebyscoreKey min Max: Follow score to delete element, delete score in [min,MaxBetween7) ZremKeyValue1 value2: Deletes the elements in the collection (8) ZremrangebyrankKey Start End: Delete elements by rank, delete rank in [Start,End] Between the (9) ZcardKey: Returns the number of collection elements (Ten) ZcountKey min MaxReturnsmin,Max] Number of elements in the interval
Second, advanced features 1, transactions

Redis implements transactional functionality through the MULTI, DISCARD, EXEC, and WATCH four commands, and support for transactions is now relatively straightforward. Redis can only guarantee that commands in one client-initiated transaction can be executed consecutively, but not in the middle of the other client's commands.

Since Redis is a single-threaded process for all client requests, it is easy to do so. In general, Redis will process and return processing results immediately after receiving a command from a client, but when a client issues a multi command in a connection, the connection goes into a transaction context, and the subsequent command is not executed immediately, but is first placed in a queue. When the EXEC command is received from this connection, Redis executes all the commands in the queue sequentially. The results of all commands are packaged together and returned to the client. The connection then ends the transaction context.

Example:

Redis127. 0. 0. 1: 6379>MultiOKRedis127. 0. 0. 1: 6379>incr aQUEUEDRedis127. 0. 0. 1: 6379>incr bQUEUEDRedis127. 0. 0. 1: 6379>exec1. (integer) 12. (integer) 1
2. Persistence

Redis is an in-memory database that supports persistence, which means that Redis often needs to synchronize in-memory data to disk to ensure persistence. Redis supports two persistence modes, one is snapshotting (snapshot) is the default, and the other is the way Append-only file (abbreviated AOF).

    • Snapshot snapshotting

Snapshots are the default persistence mode. This is the way in which the in-memory data is written to the binary in a snapshot, the default file name is Dump.rdb. You can automatically make snapshot persistence by configuring settings. We can configure Redis to take snapshots automatically if more than M key is modified in n seconds, the following is the default snapshot save configuration:

9001  #900秒内如果超过1个key被修改,则发起快照保存30010#300秒内容如超过10个key被修改,则发起快照保存6010000


    • append-only file (AOF)

AOF is more persistent than snapshot mode, because Redis appends each received write command to a file by using the Write function (default is appendonly.aof) when aof persistence is used.
When Redis restarts, the contents of the entire database are rebuilt in memory by re-executing the write commands saved in the file. Of course, because the OS caches write modifications in the kernel, it may not be written to disk immediately. The persistence of this aof method is also likely to lose some of the modifications. But we can tell Redis through the configuration file that we want to force the OS to write to disk through the Fsync function.
There are three ways of doing this:

yes           #启用aof持久化方式# appendfsync always   #每次收到写命令就立即强制写入磁盘,最慢的,但是保证完全的持久化,不推荐使用appendfsync everysec     #每秒钟强制写入磁盘一次,在性能和持久化方面做了很好的折中,推荐# appendfsync no    #完全依赖os,性能最好,持久化没保证
3, master-slave replication

Redis supports master-slave replication, and the configuration is relatively straightforward. Master-slave replication enables the backup and redundancy of data to build highly available systems. When Master does not work properly, you can switch slave to master.

Principle Process

After the slave is started and connected to master, it will actively send a sync command. Master will then start the background disk process and collect all the received commands to modify the dataset, and master will transfer the entire database file to slave to complete a full synchronization once the background process has finished executing. The slave server then disks and loads the database file data into memory after it receives it. After that, Master continues to pass all the modified commands that have been collected, and the new modification commands to Slaves,slave will execute these data modification commands at this time to achieve final data synchronization.

4, publish the subscription

A publish Subscription (PUB/SUB) is a message communication pattern that is primarily designed to decouple the coupling between a message publisher and a message subscriber, which is similar to the observer pattern in design patterns.
Pub/sub not only solves the direct code level coupling between publishers and subscribers, but also solves the coupling between the two on the physical deployment.
As a pub/sub server, Redis serves as a message routing feature between subscribers and publishers. Subscribers can subscribe to Redis server with the subscribe and Psubscribe commands for the type of message they are interested in, and Redis calls the message type channel. When a publisher sends a specific type of message to Redis server through the Publish command. All clients subscribing to this message type receive this message. The delivery of the message here is many-to-many. A client can subscribe to multiple channel, or it can send messages to multiple channel.

Shows the relationship between channel Channel1 and the three client--client2, CLIENT5, and client1 subscribing to this channel:

When a new message is sent to channel Channel1 via the PUBLISH command, the message is sent to the three clients subscribed to it:

Summarize:

From the introduction of Redis to simple operation commands, and then understand its transactions, persistence, master-slave replication and other features, I hope in the future use of the project will be handy, as for the other features of Redis, such as virtual memory, we can be a little bit deeper in the future. And in the actual application process will also appear a variety of problems, then one by one to solve.

NoSQL's in-depth redis

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.