Redis is an open source, write with ANSI C language, support network, memory-based, persistent,Key-value database, and provides APIs in multiple languages. It is a data structure server for memory storage that can be used as a database, cache, and Message Queuing agent. By data all in-Momery's approach ensures high-speed access while providing data landing capabilities, which is the main application scenario for Redis. Reids built-in replication, LUA scripting, LRU retract, things, and different levels of disk persistence, while providing high availability through Redis Sentinel and automatic partitioning via Redis cluster. Redis supports data types such as strings, hash tables, lists, collections, ordered collections, bitmaps, hyperloglogs, and so on. Redis's most commonly used data types: string, hash,List, set, sorted set, pub/Sub, transactions. string type string is a simple key-value type, value is not just a string, it can be a number. Common commands: Set, GET, DECR, INCR, Mget, and so on. In addition to providing operations like get, set, INCR, DECR, and so on, Redis provides the following memcached: (1) gets the string length;2) toward the string append content;3) to set and get a section of the string;4) sets and gets the string of one (bit);5) Bulk Set the contents of a series of strings;hash type hash is ideal for storing objects. Common commands: Hget, Hset, Hgetall and so on. Application Scenario: Store Some structured data, such as the user's nickname, age, gender, points, etc., to store a user information object data. Let's take a simple example to describe the application scenario for the hash, for example, we store a user information object data that contains the following information: (1) The user ID is the key for the lookup;2The stored value includes information such as name, age, birthday, etc.1, Instance parsing: (1) key is the user Id,value is a map. (2The key of this map is the property name of the member, and value is the property value;3) The data can be modified and accessed directly through its internal map key (Redis called internal map key field), that is, key (username ID) +Field (property name) to manipulate the corresponding attribute data. 2, note: (1Redis provides an interface (Hgetall) that can fetch all the property data directly, but if the internal map has many members, it involves traversing the entire map. (2because of the Redis single-threaded model, this traversal operation can be time-consuming, and it is important to note that other clients ' requests are completely unresponsive. The list type list type is essentially a doubly linked list in which each element is a string type, which allows the list to be used as either a stack or as a queue. The list type is often used for Message Queuing services to complete the exchange of messages between multiple programs. Common commands: Lpush, Rpush, Lpop, Rpop, Lrange, etc. Application scenario: Achieve the latest message ranking and other functions, as well as Message Queuing. Simple Message Queuing Example analysis: (1assuming that an application executes Lpush adds new elements to the list, we usually refer to such a program as "producer (producer)";2while another application is performing a rpop operation to extract elements from the list, we call this program "Consumer (consumer)";3In the process of consumer consumption of messages, it is necessary to keep calling Rpop to see if messages are pending in the list. A link is initiated once per call, causing unnecessary waste. (4In addition, if the producer speed is greater than the consumer speed, the message queue length will always increase, long time will occupy a large amount of memory space;5So, you can use the Brpop command, which is returned only if there are elements, and no will block until the timeout returns null. The set type set type is an unordered collection of type string. The concept of a set set is a combination of a bunch of distinct values. The set element can contain a maximum of (2 of the 32-time Square-1) of elements. The set internal implementation is a value that is always null hashmap. The functionality provided externally by set is a list-like feature, especially when set can be automatically weight-drained. Common commands: Sadd, Spop, Smembers, sunion and so on. Set is a good choice when you need to store a list of data, and you don't want duplicate data to appear. and set provides an important interface to determine whether a member is within a set set, which is not available by list. With the set data structure, it is possible to store a collection of datasets, such as in a microblog application, in which all followers of a user can exist in a single set, with all their fans in one set. Redis also provides for the collection of intersection, set, difference sets and other operations, can be very convenient to achieve such as common concern, common preferences, two-degree friends and other functions. Zset type and set, sorted set is also a collection of stirng type elements. The difference is that each element is associated with a double type of score, and the order of the elements is determined by score. The sorted set is inserted in an ordered, automatic sort. Common commands: Zadd, Zrange, Zrem, Zcard and so on. When you need an ordered and non-repeating collection list, you can choose the sorted set data structure. Examples of applications: (1For example, to store the class's results, the collection value can be the student's school number, and score can be the result. (2Leaderboard Application, according to the score list TOPN users and so on. Pub /the Subsubscribe, unsubscribe, and publish three commands implement a publish-subscribe generic. The sender (the client sending the message) does not send the information directly to a specific recipient (the client receiving the information), but instead sends the information to the channel, which is then forwarded by the channel to all subscribers who are interested in the channel. The sender does not need to know any information about the Subscriber, and the Subscriber does not need to know which client is sending it a message, as long as it focuses on the channel of interest. Publish/Subscribe in Redis, it is designed to be lightweight and concise, it does the basic ability to publish and subscribe to messages, but does not yet provide various enterprise-class features such as message persistence. A REDIS client publishes a message, multiple Redis client subscriptions, a message that is posted is lost, Redis does not persist the published message, and a message subscriber can only receive a post-subscription message, and the previous message in the channel is not available. The message publisher, the publish client, does not need an exclusive link, and you can use the same redis at the same time as the publish message-Client links for other operations (such as INCR, etc.); A message subscriber, the Subscribe client, needs an exclusive link, that is, during subscribe, Redis-The client cannot be interspersed with other operations. At this point the client waits for the publish message in a blocking manner, so subscribe needs to use a separate link, even if it needs to be used in an extra thread. TCP Default connection time is fixed, if the sub end of the world does not receive the pub-side message, or pub side no message generated, the sub-side of the connection will be forced to recycle. This requires special means to solve, with a timer to simulate the keepalive mechanism between pub and sub, timer time can not exceed the TCP maximum connection time. Once the subscribe side disconnects, it will lose some of the message, that is, the message will be lost during the link failure, so you need to consider the Redis list to persist, and if you are very concerned about each message, then you should do some extra work on Redis, If you want the subscription to be persistent, then the following design ideas can be used for reference: (1) Subscribe: First add "Subscriber ID" to a set set, which holds "active subscribers", and the Subscriber ID marks each unique subscriber, which is the "Active Subscriber Collection". (2) Subscribe-side Open subscription operation, and based on Redis to create a Subscriber ID key to the list data structure, this list stores all the unused messages, this list is called "subscriber message Queue";3publish end: After each message is published, the publish side needs to traverse the active Subscriber collection and sequentially append the message to each Subscriber message queue;4so far, we can basically guarantee that every message we publish will persist in each Subscriber message queue;5) The subscribe side, each receiving a subscription message, after consumption week, must delete its own "subscriber Message Queue" header of a message;6when the subscribe side starts, if it finds its own "subscriber message queue" with the remaining records, it will first consume these messages before subscribing. The above method can guarantee the successful arrival of the message must be consumed without losing transactionsRedis transactions can execute multiple commands at once. A transaction goes through three stages from start to execution: (1) Start the transaction (2) command to queue (3executing a transactional transaction is a separate quarantine operation: All commands in a transaction are serialized and executed sequentially. The transaction is not interrupted by a command request sent by another client during execution. The execution of a single Redis command is atomic, but Redis does not add any mechanism to maintain atomicity on the transaction, so the execution of the Redis transaction is not atomic. A transaction can be understood as a packaged bulk execution script, but a bulk instruction is not an atomic operation, and the failure of one of the instructions in the middle does not result in a rollback of the previously made instruction, nor does it cause subsequent instructions to fail. Multi,exec, discard, and watch commands are the basis for redis transactions. Multi: (1The Multi command is used to open a transaction, which always returns OK. (2after the multi command executes, the client can continue to send any number of commands to the server;3These commands are not executed immediately, but are placed in a queue;4When the EXEC command is called, all commands in the queue are executed. exec: (1the EXEC command is responsible for triggering and executing all commands in the transaction;2If the client has opened a transaction with multi and has not successfully executed the EXEC command because of a wire break, then all the commands in the transaction will not be executed. (3on the other hand, if the client succeeds in executing the EXEC command after the transaction is opened, all commands in the transaction will be executed. Discard: (1by calling discard, the client can empty the transaction queue and discard the execution transaction. Watch: (1) Watch command can provide check-and-for redis transactionsSet (CAS) behavior. (2Watch allows the EXEC command to perform conditionally: The transaction can only be executed if all the monitored keys have not been modified, and if this premise is not met, the transaction will not be executed. (3If you use watch to monitor a health with an expiration date, the transaction can still be executed even if the health is expired. (4Watch can be called multiple times, and the monitoring of the health will take effect after the watch is executed until exec is called. (5When exec is called, monitoring of all health is canceled regardless of whether the transaction was executed successfully. (6) When the client disconnects, the client's monitoring of the health will also be canceled.
Redis data types