search
HomeBackend DevelopmentPHP TutorialWhat 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.

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!

Statement
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 admin@php.cn
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),