preface

Redis is very hot in the tech community right now. Redis has come a long way from a small personal project at Antirez to becoming a standard in the in-memory data storage industry.

The following series of best practices, so that most people can use Redis correctly, xiaobian in learning Redis also organized a Redis technology mind map, to share with you!

10 tips on how to use Redis correctly

1. Stop using KEYS *

Okay, challenging this command may not be a good way to start this post, but it’s probably the most important point.

Many times when we are looking at the statistics of a Redis instance, we will quickly type “KEYS *” so that the key information is clearly displayed. To be fair, the tendency from a programmatic point of view is to write pseudocode like this:

for key in 'keys *':
 doAllTheThings()
Copy the code

But when you have 13 million keys, execution slows down. Because KEYS is O(n), where n is the number of KEYS to return, the complexity of this command depends on the size of the database. And during this operation, any other commands cannot be executed in your instance.

As an alternative command, take a look at SCAN, which allows you to execute in a friendlier way… SCAN scans the database in incremental iteration. This is done based on the cursor iterator, so you can stop or continue as you see fit.

Recommended: A deadly Redis command, loss of 4 million!

2. Identify the culprits that slow down Redis

Because Redis does not have very detailed logs, it is difficult to know what is going on inside a Redis instance. Fortunately, Redis provides a command statistics tool that looks like this:

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.10Copy the code

This tool allows you to view a snapshot of all command statistics, such as how many times the command was executed and the number of milliseconds it took to execute the command (total and average time per command).

Simply execute the CONFIG RESETSTAT command to reset, and you’ll get a completely new statistic.

3. Use the Redis-benchmark results as a reference, rather than generalizing

Salvatore, the father of Redis, said, “Testing Redis by executing GET/SET is like testing how well a Ferrari wiper cleans a mirror on a rainy day.” A lot of times people come to me and they want to know why their Redis-Benchmark statistic is below optimal. But we have to take into account different realities, such as:

  • What client running environment may be limited by?
  • Is it the same version number?
  • Is the performance in the test environment consistent with the environment in which the application will be run?

The results of the Redis-benchmark test provide a Benchmark to ensure that your Redis-Server will not run in abnormal conditions, but you should never use it as a true “stress test”. Stress testing needs to reflect how the application operates and needs an environment that is as similar to production as possible.

4. Hashes is your best choice

Let’s introduce Hashes in an elegant way. Hashes will bring you an experience you have never experienced before. I’ve seen many key constructs like this before:

foo:first_name
foo:last_name
foo:address
Copy the code

In the example above, foo might be the username of a user, where each entry is a separate key. This increases the room for error and unnecessary keys. Use hash instead, and you’ll be surprised to see that only one key is required:

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 the code

5. Set the lifetime of the key value

Whenever possible, take advantage of key timeouts. A good example is to store something like a temporary authentication key.

When you look for an authorization key — take OAUTH for example — you usually get a timeout. So when setting the key, set to the same timeout period, Redis will automatically clear for you! Instead of using KEYS * to iterate over all KEYS, how convenient is that?

6. Choose an appropriate recycling strategy

While we’re on the subject of cleanup keys, let’s talk about recycling strategies. When the Redis instance space is full, an attempt is made to reclaim some of the keys. Depending on how you use it, I strongly recommend volatile- lRU — if you have timed out the key.

But if you’re running something like a cache and don’t have a timeout mechanism for keys, consider using the AllKeys-LRU recycle mechanism. My advice is to check out the options here first.

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

If you must ensure that critical data can be put into an instance of Redis, I strongly recommend putting it in a try/except block. Almost all Redis clients use a “send and forget” policy, so you often need to consider whether a key is actually placed in the Redis database. The complexity of putting try/expect into Redis commands is beyond the scope of this article, just that it ensures that the important data goes where it should.

8. Don’t run out of instances

Whenever possible, spread out the workload of multiple Redis instances. Redis has supported clustering since version 3.0.0. Redis clustering allows you to separate out some keys that contain master/slave patterns based on key ranges. The “magic” behind the complete cluster can be found here.

But if you’re looking for a tutorial, this is the place to go. If clustering is not an option, consider namespaces and spread your keys across multiple instances. There’s an excellent review of how data is allocated at redis. IO.

9. The more cores, the better? !

Wrong, of course. Redis is a single-threaded process. Why can Redis single-threaded process support high concurrency? Even with persistence enabled, it only consumes two kernels at most. Unless you plan to run multiple instances on a single host — hopefully only in a development test environment! Otherwise, no more than 2 kernels are required for a Redis instance.

10. High availability

So far, Redis Sentinel has been thoroughly tested and implemented by many users in production environments (including ObjectRocket). If your application relies heavily on Redis, you’ll need to come up with a high availability solution to keep it online.

The last

Redis is an open source, memory-based persistent non-relational database storage system. In actual projects, Redis can be used as a cache or message server. Redis is also a non-relational database widely used in the Internet. Xiaofian to share the skills above, part of the reference to a Redis combat more than 300 pages of learning notes, pay attention to the public number: Kirin to change the bug, more Java learning technology, welcome to exchange, like the article remember to pay attention to me like yo, thank you for your support!