search
HomeBackend DevelopmentPHP TutorialTen tips for using Redis correctly

Ten tips for using Redis correctly

Dec 14, 2017 pm 01:59 PM
redisuseSkill

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()

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

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

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"

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
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 Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.