1. Foreword
At work, we often encounter situations where we need to delete the keys of certain rules in batches, such as the cached course data "course-course uid", Course uid is a variable, we need to delete data similar to "course-*". However, although redis provides commands for batch querying keys of this type, it does not provide commands for batch deletion of certain types of keys.
Now I will sort out the solutions, I hope it can help everyone.
2. Solution
Let’s see how we solve it first.
1. First enter the redis client
cd redis所在目录/src ./redis-cli
2. Initialize data and simulate data
127.0.0.1:6379> set course-1 1 OK 127.0.0.1:6379> set course-2 2 OK 127.0.0.1:6379> set course-3 3 OK
3. You can see it through the keys command. Now there are three above key
127.0.0.1:6379> keys course-* 1) "course-3" 2) "course-2" 3) "course-1"
4. Exit the redis client
127.0.0.1:6379> exit
5.1. Local batch deletion of key
./redis-cli keys "course-*" | xargs ./redis-cli del
The 3 related keys of course-* have been deleted just now.
Principle analysis:
First execute the keys command through the redis client, fuzzy search out all the keys, and use the xargs command to use the previously queried keys as the input of the subsequent redis del command.
The final execution result can be understood as
(Learning video sharing: redis video tutorial)
1. Fuzzy query
keys "course-*"
Query the three keys of course-1 course-2 course-3 above
2. Execute deletion key
The three keys of del come from the previous keys query
del course-1 course-2 course-3
5.2. Remote batch deletion of keys
Often when we develop, redis is public. Maybe redis is not local and we can delete it remotely through the redis client
./redis-cli -h redis所在服务器ip -p 端口 keys "course-*" |xargs ./redis-cli -h redis所在服务器ip -p 端口 del
3 , Supplementary knowledge
1. Redis of a remote machine
The following example demonstrates how to connect to the redis service with the host 127.0.0.1, the port 6379, and the password mypass.
redis-cli -h 127.0.0.1 -p 6379 -a "mypass"
2. xargs command
The xargs command is a filter for passing parameters to other commands, and it is also a tool for combining multiple commands. Detailed courseware http://man.linuxde.net/xargs
Related recommendations: redis database tutorial
The above is the detailed content of redis deletes keys of certain rules in batches. For more information, please follow other related articles on the PHP Chinese website!