Home >Backend Development >PHP Tutorial >What are the data types of redis? Summary of various data types of redis
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.
#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.
It is an in-memory data structure server that can be used as a database, cache, and message queue agent.
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.
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.
Redis supports data types such as strings, hash tables, lists, sets, ordered sets, bitmaps, and hyperloglogs.
The most commonly used data types of redis: stirng, hash, list, set, sorted set, pub/sub, transactions.
The string type is a simple key-value type. The value is not only a string, but also a number.
Commonly used commands: set, get, decr, incr, mget, etc.
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;
(2) The stored value includes name, age, birthday and other information
(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) 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.
(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.
And set provides an important interface to determine whether a member is in a set collection, which list cannot provide.
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.
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.
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.
sorted set is insertion ordered, that is, automatically sorted.
Commonly used commands: zadd, zrange, zrem, zcard, etc.
When you need an ordered and non-duplicate list of sets, you can choose the sorted set data structure.
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.
The three commands subscribe, unsubscribe and publish implement publishing and subscribing generics.
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.
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.
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.
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.
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;
The message subscriber, that is, the subscribe client, needs an exclusive link, that is, during the subscribe period, redis-client cannot intersperse other operations.
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.
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.
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.
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;
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.
The above method can ensure that successfully arrived messages must be consumed and not lost
redis A transaction can execute multiple commands at once.
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 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!