What are the data types of redis? Summary of various data types of redis

不言
Release: 2023-04-04 07:32:02
Original
6653 people have browsed it

This article brings you what are the redis data types? The summary of each data type of redis has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

  1. #redis is an open source log-type, key-value database written in ANSI C language, supports network, can be based on memory, and can also be persisted. And provides APIs in multiple languages.

  2. It is an in-memory data structure server that can be used as a database, cache, and message queue agent.

  3. Ensures high-speed access by keeping all data in-momery, and at the same time provides the function of data landing. This is the main applicable scenario of redis.

  4. reids has built-in replication, Lua scripts, LRU recovery, transactions, and different levels of disk persistence functions. It also provides high availability through redis Sentinel and automatic partitioning through Redis Cluster.

  5. Redis supports data types such as strings, hash tables, lists, sets, ordered sets, bitmaps, and hyperloglogs.

  6. The most commonly used data types of redis: stirng, hash, list, set, sorted set, pub/sub, transactions.

String type

  1. The string type is a simple key-value type. The value is not only a string, but also a number.

  2. Commonly used commands: set, get, decr, incr, mget, etc.

  3. In addition to providing the same get, set, incr, decr and other operations as memcached, redis also provides the following operations:

(1) Get the length of the string;
(2) Append content to the string;
(3) Set and get a certain section of the string;
(4) Set and get a certain section of the string Bit (bit);
(5) Set the contents of a series of strings in batches;

Hash type

  1. ##hash is particularly suitable for storing objects.

  2. Commonly used commands: hget, hset, hgetall, etc.

  3. Application scenario: Store some structured data, such as the user's nickname, age, gender, points, etc., and store a user information object data.

  4. Let’s take a simple example to describe the application scenario of Hash. For example, we store a user information object data, including the following information:

(1) The user id is the key to be searched;

(2) The stored value includes name, age, birthday and other information

1. Example analysis:

(1) The key is User id, value is a Map.

(2) The key of this Map is the attribute name of the member, and the value is the attribute value;
(3) In this way, the modification and access to the data can be directly through its internal Map key (called internal in redis) The key of Map is field), that is, key (user name id) field (attribute name) can operate the corresponding attribute data.

2. Note:

(1) Redis provides an interface (hgetall) that can directly obtain all attribute data. However, if there are many members of the internal Map, it involves traversing the entire Map. operate.

(2) Due to the single-threaded model of redis, this traversal operation may be time-consuming, and other client requests may not be responded to at all. This needs to be noted.

List type

  1. The list type is essentially a doubly linked list in which each element is of type string. This allows the list to be used as either a stack or a queue. .

  2. The list type is often used in message queue services to complete message exchange between multiple programs.

  3. Commonly used commands: lpush, rpush, lpop, rpop, lrange, etc.

  4. Application scenarios: Implement functions such as latest message ranking, as well as message queues.

  5. Simple message queue example analysis:

(1) Suppose an application executes lpush to add new elements to the linked list. We usually Such a program is called a "producer";

(2) While another application is performing the rpop operation to remove elements from the linked list, we call such a program a "consumer";
(3) During the process of consumer consuming messages, rpop needs to be called continuously to check whether there are pending messages in the list. Each call will initiate a link, causing unnecessary waste.
(4) In addition, if the producer speed is greater than the consumer speed, the length of the message queue will continue to increase, which will occupy a lot of memory space over time;
(5) Therefore, you can use the brpop command, which only Returns if there is an element, otherwise it will block until timeout and return null.

Set type

  1. The set type is an unordered collection of string type.

  2. The concept of a set is a collection of unique values.

  3. set elements can contain up to (2 to the 32nd power - 1) elements.

  4. The internal implementation of set is a HashMap whose value is always null.

  5. The external functions provided by set are similar to those of list. The special feature is that it can automatically eliminate duplicates during set.

  6. Commonly used commands: sadd, spop, smembers, sunion, etc.

  7. When you need to store a list of data and do not want duplicate data, set is a good choice.

  8. And set provides an important interface to determine whether a member is in a set collection, which list cannot provide.

  9. Using the set data structure, some collective data can be stored. For example, in a Weibo application, all followers of a user can be stored in a set, and all his fans can be stored in a set. A collection.

  10. Redis also provides operations such as intersection, union, and difference for collections, which can be very convenient to implement functions such as common attention, common preferences, and second-degree friends.

Zset type

  1. Like set, sorted set is also a collection of stirng type elements. The difference is that each element is associated with a double type score, and the order of the elements is determined by the score.

  2. sorted set is insertion ordered, that is, automatically sorted.

  3. Commonly used commands: zadd, zrange, zrem, zcard, etc.

  4. When you need an ordered and non-duplicate list of sets, you can choose the sorted set data structure.

  5. Application examples:

(1) For example, to store the grades of the whole class, the set value can be the student number of the classmate, and score It can be grades.
(2) Ranking application, lists topN users based on scores, etc.

pub/sub

  1. The three commands subscribe, unsubscribe and publish implement publishing and subscribing generics.

  2. The sender (the client that sends the information) does not directly send the information to the specific recipient (the client that receives the information), but sends the information to the channel (channel), The channel then forwards the information to all subscribers who are interested in the channel.

  3. The sender does not need to know any information about the subscriber, and the subscriber does not need to know which client sent it the information. It only needs to pay attention to the channel that interests it.

  4. Publish/Subscribe in redis, which is designed to be very lightweight and concise. It achieves the basic capabilities of message publishing and subscription; however, it has not yet provided information about message persistence and other aspects. enterprise-level features.

  5. One redis client publishes messages, and multiple other redis clients subscribe to messages. The published messages are lost as soon as they are sent. Redis will not persist the published messages; message subscribers can only get After the message is subscribed, the previous messages in the channel cannot be obtained.

  6. The message publisher, that is, the publish client, does not need an exclusive link. You can use the same redis-client link to perform other operations (such as incr, etc.) while publishing the message;

  7. The message subscriber, that is, the subscribe client, needs an exclusive link, that is, during the subscribe period, redis-client cannot intersperse other operations.

  8. At this time, the client waits for messages from the publish side in a blocking manner, so subscribe needs to use a separate link or even use it in an additional thread.

  9. tcp default connection time is fixed. If the sub side does not receive the pub side message in this world, or the pub side does not generate a message, the sub side connection will be forcibly recycled.

  10. This requires special means to solve. Use a timer to simulate the keep-alive mechanism between pub and sub. The timer time cannot exceed the maximum tcp connection time.

  11. Once the subscribe end disconnects the link, some messages will be lost, that is, the messages during the link failure period will be lost. Therefore, the redis list needs to be considered here for persistence;

  12. If you are very concerned about each message, then you should do some additional supplementary work based on redis. If you want the subscription to be durable, then the following design ideas can be used for reference:

(1) Subscribe side: First add "subscriber id" to a set collection. This set collection saves "active subscribers"; the subscriber id marks each unique subscriber. This set For the "active subscriber collection".
(2) The subscribe side starts the subscription operation and creates a list data structure with the subscriber ID as the key based on redis. This list stores all unconsumed messages. This list is called the "subscriber message queue" ;
(3) Publish side: After each message is published, the publish side needs to traverse the active subscriber collection and append the published message to the end of each "subscriber message queue" in turn;
(4 ) So far, we can basically guarantee that every message published will be persistently stored in each "subscriber message queue";
(5) On the subscribe side, every time a subscription message is received, it will be Afterwards, you must delete a message at the head of your "Subscriber Message Queue";
(6) When the subscribe end is started, if you find that there are residual records in your "Subscriber Message Queue", these will be consumed first message and then subscribe.

  1. The above method can ensure that successfully arrived messages must be consumed and not lost

transactions

  1. redis A transaction can execute multiple commands at once.

  2. A transaction will go through three stages from start to execution:

(1) Start transaction
(2) Command enqueue
(3) Execute transaction

A transaction is a separate isolation operation: all commands in the transaction will be serialized and executed in order.

During the execution of the transaction, it will not be interrupted by command requests sent by other clients.

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 batch execution script, but batch instructions are not atomic operations. The failure of an instruction in the middle will not cause the rollback of previous instructions, nor will it cause subsequent instructions. Don't do it.

The multi, exec, discard and watch commands are the basis of redis transactions.

multi:

(1) The multi command is used to start a transaction, and it always returns ok.
(2) After the multi command is executed, the client can continue to send any number of commands to the server;
(3) These commands will not be executed immediately, but will be placed in a queue;
( 4) When the exec command is called, all commands in the queue will be executed.

exec:

(1) The exec command is responsible for triggering and executing all commands in the transaction;
(2) If the client uses multi to open a After the transaction, if the exec command is not successfully executed due to disconnection, all commands in the transaction will not be executed.
(3) On the other hand, if the client successfully executes the exec command after opening the transaction, all commands in the transaction will be executed.

discard:

(1) By calling discard, the client can clear the transaction queue and give up executing the transaction.

watch:

(1) The watch command can provide check-and-set (CAS) behavior for redis transactions.
(2) watch enables the exec command to be executed conditionally: the transaction can only be executed under the premise that all monitored keys have not been modified. If this condition is not met, the transaction will not be executed.
(3) If you use watch to monitor a key with an expiration time, even if the key expires, the transaction can still be executed.
(4) watch can be called multiple times, and the monitoring of health takes effect from the time watch is executed until exec is called.
(5) When exec is called, regardless of whether the transaction is successfully executed, the monitoring of all health will be cancelled.
(6) When the client disconnects the link, the client's monitoring of the health will also be cancelled.

Related recommendations:

Redis data type--string

##Redis basic data type and related operations

The above is the detailed content of What are the data types of redis? Summary of various data types of redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!