Home Backend Development PHP Tutorial Ten tips for using Redis correctly

Ten tips for using Redis correctly

Dec 14, 2017 pm 01:59 PM
redis use Skill

Redis is very popular in the current technology community. From a small personal project from Antirez to becoming the industry standard for in-memory data storage, Redis has come a long way. Most people can use Redis correctly. Below we will explore 10 tips for using Redis correctly.

1. Stop using KEYS *

Okay, starting this article by challenging this command may not be a good way, but it may indeed be the most important a little bit. Many times when we pay attention to the statistics of a redis instance, we will quickly enter the "KEYS *" command so that the key information will be clearly displayed. To be fair, from a programming perspective, we tend to write pseudocode like the following:


for key in 'keys *': 
 doAllTheThings()
Copy after login

But when you have 13 million keys, the execution speed will change. slow. Because the time complexity of the KEYS command is O(n), where n is the number of keys to be returned, the complexity of this command depends on the size of the database. And during the execution of this operation, no other commands can be executed in your instance.

As an alternative command, take a look at SCAN, which allows you to perform in a more friendly way... SCAN scans the database in an incremental iteration. This operation is done based on the cursor's iterator, so you can stop or continue at any time as you see fit.

2. Find out the culprit that slows down Redis

Since Redis does not have very detailed logs, it is very difficult to know what is done inside the Redis instance. difficult. Fortunately, Redis provides a command statistics tool like the following:


127.0.0.1:6379> INFO commandstats 
# Commandstats 
cmdstat_get:calls=78,usec=608,usec_per_call=7.79 
cmdstat_setex:calls=5,usec=71,usec_per_call=14.20 
cmdstat_keys:calls=2,usec=42,usec_per_call=21.00 
cmdstat_info:calls=10,usec=1931,usec_per_call=193.10
Copy after login

Through this tool, you can view snapshots of all command statistics, such as how many times the command has been executed, and how many times the command has been executed. The number of milliseconds spent (total time and average time of each command)

You only need to simply execute the CONFIG RESETSTAT command to reset it, so that you can get a brand new statistical result.

3. Use the Redis-Benchmark results as a reference instead of generalizing

Salvatore, the father of Redis, said: “Testing Redis by executing the GET/SET command is Like testing how well a Ferrari's windshield wipers clean the mirrors on a rainy day." Many times people come to me and they want to know why their Redis-Benchmark statistics are lower than the optimal results. But we must take into account various real situations, such as: What client running environment restrictions may

  • have? Is

  • the same version number?

  • Is the performance in the test environment consistent with the environment in which the application will be run?

The test results of Redis-Benchmark provide a benchmark point to ensure that your Redis-Server will not run in an abnormal state, but you should never take it as a real " pressure test". Stress testing needs to reflect how the application is running and needs an environment that is as similar to production as possible.

4. Hashes is your best choice

Introduce hashes in an elegant way. Hashes will bring you an unprecedented experience. I have seen many key structures similar to the following before:


foo:first_name 
foo:last_name 
foo:address
Copy after login

In the above example, foo may be the username of a user, and each item in it They are all a single key. This increases the room for error and unnecessary keys. Use hash instead, you will be surprised to find that you only need one key:


127.0.0.1:6379> HSET foo first_name "Joe" 
(integer) 1 
127.0.0.1:6379> HSET foo last_name "Engel" 
(integer) 1 
127.0.0.1:6379> HSET foo address "1 Fanatical Pl" 
(integer) 1 
127.0.0.1:6379> HGETALL foo 
1) "first_name" 
2) "Joe" 
3) "last_name" 
4) "Engel" 
5) "address" 
6) "1 Fanatical Pl" 
127.0.0.1:6379> HGET foo first_name 
"Joe"
Copy after login

5. Set the survival time of the key value

Whenever possible, take advantage of key timeouts. A good example is storing something like a temporary authentication key. When you look up an authorization key - take OAUTH as an example - you usually get a timeout. In this way, when setting the key, set it to the same timeout period, and Redis will automatically clear it for you! It is no longer necessary to use KEYS * to traverse all keys. How convenient?

6. Choose the appropriate recycling strategy

Since we have talked about the topic of clearing keys, let’s talk about the recycling strategy. When the Redis instance space is filled up, it will try to reclaim some keys. Depending on your usage, I strongly recommend using the Volatile-lru strategy - provided you have set a timeout on the key. But if you are running something similar to a cache and do not set a timeout mechanism for keys, you can consider using the allkeys-lru recycling mechanism. My suggestion is to check out what's possible here first.

7. If your data is very important, please use Try/Except

If you must ensure that critical data can be put into the Redis instance, I It is highly recommended to put this in a try/except block. Almost all Redis clients adopt the "send and forget" strategy, so it is often necessary to consider whether a key is actually placed in the Redis database. The complexity of putting try/expect into Redis commands is not what this article is about. You just need to know that doing so ensures that important data is placed where it should be.

8. Don’t exhaust an instance

Whenever possible, spread the workload of multiple redis instances. Starting from version 3.0.0, Redis supports clusters. Redis Cluster allows you to separate out some keys that contain master/slave modes based on key ranges. The complete "magic" behind clustering can be found here. But if you are looking for tutorials, this is the perfect place. If clustering isn't an option, consider namespaces and spreading your keys across multiple instances. Regarding how to distribute data, there is this excellent review on the redis.io website.

9. Are the more cores the better?

Of course it is wrong. Redis is a single-threaded process and only consumes a maximum of two cores even with persistence enabled. Unless you plan to run multiple instances on a single host - hopefully only in a development and test environment! ——Otherwise, there is no need for more than 2 cores for a Redis instance.

10. High availability

So far Redis Sentinel has been thoroughly tested, and many users have applied it to production environments (including ObjectRocket). If your application relies heavily on Redis, you need to come up with a high availability solution to ensure that it does not go offline. Of course, if you don’t want to manage these things yourself, ObjectRocket provides a high-availability platform and 7×24-hour technical support. If you are interested, you can consider it.

Related recommendations:

Correct method to unlock redis lock

Redis optimization experience summary

Summary of common methods for operating redis in php

The above is the detailed content of Ten tips for using Redis correctly. For more information, please follow other related articles on the PHP Chinese website!

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 admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles