《 Get along well with Redis》 Series of articles Redis Basic and advanced application of . This article is about 《 Get along well with Redis》 The first series 【13】 piece , For the latest series of articles, please go to official account “zxiaofan”( Point me, please. ) see , or Baidu search “ Get along well with Redis zxiaofan” that will do .
Key words of this article : Get along well with Redis、Redis Data import 、Redis A large number of insert 、Redis Export data 、Redis Export the specified wildcard 、Redis Data deletion 、Redis Batch deletion 、Redis Delete the specified prefix key、Redis Delete the specified wildcard key;
Previous selections :《 Get along well with Redis- Two million were deleted key, Why memory is still not released ?》
The outline
- Redis Safe and efficient import of large amounts of data in production environment
- Use shell Script constructs test data
- Redis Non cluster mode imports large amounts of data
- Redis Cluster mode imports a lot of data
- Redis Production environment safe and efficient export of large amounts of data
- Redis Import and export all data
- Redis Export the specified prefix ( Specify the wildcard character ) data
- Redis Safe and efficient deletion of data in production environment
- Redis Delete known assignments key
- Redis Delete the specified prefix ( Specify the wildcard character ) data
- Practical tips
- Redis Statistics specified wildcard key The number of
- Password free connection Redis Script
- Thinking questions :Linux Can I set the script to be executable but not readable
summary :
This article will simulate the production environment , Construct a lot of test data , And complete the efficient and safe data import 、 Export data 、 Data deletion .
as everyone knows ,Redis It's single threaded , Once a command is issued, the time is blocked , It is very easy to cause a lot of command blocking , This leads to the avalanche of production environment , So this paper emphasizes that 【 Production environment 、 Safe and efficient 】 operation .
Let's Go!
1、Redis Safe and efficient import of large amounts of data in production environment
1.1、 Use shell Script constructs test data
linux The environment create dataBuild.sh Script , This script is used to generate test data , The input to the script is the amount of test data , The script is as follows :
#!/bin/sh
# init Test Data.
# Build By @zxiaofan.com
echo " Number of constructions :$1";
rm -f ./testdata.txt;
touch testdata.txt;
starttime=`date +'%Y-%m-%d %H:%M:%S'`;
echo "Start: $starttime";
for((i=0; i< $1 ;i++))
do
str='set key-';
name=${str}${i}' value'${i};
echo $name>> testdata.txt;
done
endtime=`date +'%Y-%m-%d %H:%M:%S'`;
echo "End: $endtime";
start_seconds=$(date --date="$starttime" +%s);
end_seconds=$(date --date="$endtime" +%s);
echo " This run time : "$((end_seconds-start_seconds))"s"
#echo 'show testdata';
#cat testdata.txt;
It is suggested that linux Environment creation script , Otherwise, it may be executed shell Script error $'\r': command not found. Solution :vim acc.conf.base, And then execute “:set fileformat=unix” , and wq Save it .
Next, you can execute the script to generate test data , Here we generate 30W data , After the script is executed, the current directory will generate a test data file testdata.txt.
# By @zxiaofan
# Execute script generation 30W Test data ;
[email protected]:/study/redis# ./dataBuild.sh 300000
Number of constructions :300000
Start: 2020-10-11 17:30:45
End: 2020-10-11 17:34:54
This run time : 249s
# Examples of script content ,30W The data is about 7.5M:
set key-0 value0
set key-1 value1
set key-2 value2
set key-3 value3
set key-4 value4
set key-5 value5
...
1.2、Redis Non cluster mode imports large amounts of data
Redis The government has provided us with a solution 【mass-insert】:https://redis.io/topics/mass-insert: >Using a normal Redis client to perform mass insertion is not a good idea for a few reasons: the naive approach of sending one command after the other is slow because you have to pay for the round trip time for every command. It is possible to use pipelining, but for mass insertion of many records you need to write new commands while you read replies at the same time to make sure you are inserting as fast as possible.
>Only a small percentage of clients support non-blocking I/O, and not all the clients are able to parse the replies in an efficient way in order to maximize throughput. For all of these reasons the preferred way to mass import data into Redis is to generate a text file containing the Redis protocol, in raw format, in order to call the commands needed to insert the required data.
Which translates as :
- Every Redis It takes a certain time for the client's command to execute and return the result ;
- Only a few clients support asynchronous I/O Handle , So even if you use multiple Redis Concurrent client insertion does not improve throughput either ;
- The suggested solution is : Insert the data to be inserted to Redis Protocol generated text file and then imported .
Redis 2.6 And above ,redis-cli Support pipeline mode pipe mode( Pipeline mode ), This pattern is specifically designed to perform large-scale inserts .
Let's have a real fight , The pipeline mode Import command is as follows :
cat testdata.txt | redis-cli --pipe
We can add... Before the order time Instruction is used to count named execution time .
# By @zxiaofan
[[email protected]]$ time cat testdata.txt | ./redis-cli --pipe
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
All data transferred. Waiting for the last reply...
Last reply received from server.
errors: 0, replies: 300000
real 0m1.778s
user 0m0.039s
sys 0m0.016s
# Even on Redis Confirm whether the data is imported successfully .
127.0.0.1:6379> get key-0
"value0"
127.0.0.1:6379> get key-299999
"value299999"
127.0.0.1:6379> get key-300000
(nil)
30W data ,1.7 Seconds to complete the import . It should be noted that , If “redis-cli” command Not set to global command , You need to get into redis-cli In the directory , Then execute the following command :
# redis-cli Turned into ./redis-cli
cat testdata.txt | ./redis-cli --pipe
If you need to specify other parameters , You can do the following :
- Designated port :-p 6379
- Specify the remote host :-h 192.168.1.1
- Require password authentication :-a redisPasword
# By @zxiaofan
# Redis Import data complete command :
cat testdata.txt | ./redis-cli -h 192.168.1.1 -p 6379 -a redisPasword --pipe
1.3、Redis Cluster mode imports a lot of data
The above data import mode is for non cluster mode , How to import data in cluster mode ?
cat testdata.txt | redis-cli -c --pipe
As shown above , Use “-c” You can start the cluster mode , However, due to the cluster mode, there are multiple nodes , It is very likely that data processing fails here .
Redis Cluster mode has 16384 individual hash Slot (hash slots), Suppose the cluster has 3 Nodes ,node1 Distribute 0~5460 Slot of ,node2 Distribute 5461~10922 Slot of ,node3 Distribute 10923~16383 Slot of . Each master node in the cluster will only operate the corresponding hash Slot , according to “CRC16(key) mod 16384” Work out each key Corresponding slot , Then go to the corresponding slot Redis The node performs the operation .
HASH_SLOT = CRC16(key) mod 16384
Be careful :
In cluster mode, nodes may be added or deleted dynamically , Therefore, it is necessary to ensure the stability of cluster nodes when executing the above commands , At the same time, check the results .
2、Redis Production environment safe and efficient export of large amounts of data
2.1、Redis Import and export all data
In this case , You can use Ruby Open source tools redis-dump export , Official website :https://github.com/delano/redis-dump.
# redis-dump Examples of use
$ redis-dump -u 127.0.0.1:6371 > db_full.json
$ redis-dump -u 127.0.0.1:6371 -d 15 > db_db15.json
$ < db_full.json redis-load
$ < db_db15.json redis-load -d 15
# OR
$ cat db_full | redis-load
$ cat db_db15.json | redis-load -d 15
# Operation with password
$ redis-dump -u :password@host:port -d 0 > db_full.json
$ cat db_full.json | redis-load -u :[email protected]:port -d 0
2.2、Redis Export the specified prefix ( Specify the wildcard character ) data
Export a large amount of data safely and efficiently , The production environment needs to be exported “ Specify the wildcard character ” data , For data or business analysis , The difficulty is 【 Export a large number of specified wildcard data safely and efficiently 】, The core in the “ Specify the wildcard character ”. Facing the production environment with large amount of data , because Redis It's single threaded , So you can't use blocking instructions .
Complete command example :
# By @zxiaofan
./redis-cli -h 192.168.1.1 -p 6379 -a password --raw --scan --pattern ' Customize pattern' > out.txt
It should be noted that : Not available here “keys” Instructions , Because this command is blocking . There are many articles on the Internet about “keys” Instructions , Don't use it with caution , Otherwise, if you are not careful, it will be really from deleting the library to running away .
2.3、redis-cli command --raw Parameter function
- The output data is raw data , Type not included ;
- Normal display of output data in Chinese , Display content is not encoded content ;
redis-cli Standard output detected is tty( terminal ) when , The returned result will be typed , such as (integer); Standard output is not tty, for example , When data is redirected to a pipe or file , Will automatically default on --raw Options , It doesn't add type information . Official statement :https://redis.io/topics/rediscli, see “Command line usage” modular .
# Standard output is tty( terminal ), Notice the result is (integer):
$ redis-cli incr mycounter
(integer) 7
# Standard output is not tty( Redirected to file ):
$ redis-cli incr mycounter > /tmp/output.txt
$ cat /tmp/output.txt
8
# Join in --raw Parameters , The results did not (integer)
$ redis-cli --raw incr mycounter
9
3、Redis Safe and efficient deletion of data in production environment
3.1、Redis Delete known assignments key
See how to quickly import large amounts of data , In fact, it is not difficult for us to find out , In essence, it is carried out Redis Text in agreement format , So when we can construct a script to delete data in advance , You can also use “--pipe” Complete the efficient deletion of a large number of data ;
# By @zxiaofan
cat deletedata.txt | redis-cli -c --pipe
# deletedata.txt The data sample :
del key-0
del key-1
del key-2
del key-3
del key-4
del key-5
del key-6
del key-7
del key-8
del key-9
...
3.2、 Delete the specified prefix ( Specify the wildcard character ) data
The order is as follows :
# By @zxiaofan
./redis-cli -h 127.0.0.1 -p 6379 -a password --scan --pattern 'key-*' | xargs ./redis-cli -h 127.0.0.1 -p 6379 -a password del {}
The output is like :
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
(integer) 12322
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
(integer) 12326
The core of the command is :
- 【--scan --pattern 'key-*'】: Use wildcard matching to specify key;
- 【| xargs】: Used to pass parameters ;
- 【del {}】: receive key And delete ;
Linux xargs command :
xargs( Spell it all in English : eXtended ARGuments) Is a filter that passes parameters to commands , It's also a tool for combining multiple commands . xargs You can input pipe or standard input (stdin) Data to command line arguments , Can also read data from the output of the file .
xargs You can also convert single or multiple lines of text input to other formats , For example, multi line to single line , Single line to multi line .
xargs The default command is echo, This means that it is piped to xargs The input will contain line breaks and white space , But by xargs To deal with , Newlines and whitespace will be replaced by spaces .
xargs It's a strong order , It can capture the output of a command , And then pass it on to another command .
Because many commands don't support | Pipes to pass parameters , So there it is xargs command .
The above command introduction is derived from :https://www.runoob.com.
xargs Generally used with pipes , Command format :
somecommand |xargs -item command
4、 Practical tips
4.1、Redis Statistics specified wildcard key The number of
We have taught you how to export or delete data in the production environment , So how do we verify that the amount of data is correct ?
With the help of “ | wc -l” that will do :
# By @zxiaofan
# The core of the command is “ | wc -l”
>./redis-cli -h 127.0.0.1 -p 6379 -a password --scan --pattern 'id:*' | wc -l
66666
4.2、 Password free connection Redis Script
In the production environment, it must be very unsafe to enter a password for every operation 、 very low The operation of , So what are the ways we can connect without entering a password redis Do you .
Save the following in the script “openredis.sh” in , Use “chmod u+x openredis.sh” Grant script executable rights . The password free here actually saves the password to the script , So pay attention to the security of this script .
# By @zxiaofan
# Connect Redis Script , If there is a password , Please change the “password” Change to the actual password
# The first parameter is the port number , The second parameter is the command to be executed ;
# If you need to specify the host , Join in -h that will do ;
Port=$1
CMD=$2
/usr/local/bin/redis-cli -p $Port -a password $CMD
Usage mode :
# Use openredis.sh see Clients Connection information
[[email protected] redis]# ./openredis.sh 6379 'info Clients'
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Clients
connected_clients:1
client_recent_max_input_buffer:51
client_recent_max_output_buffer:0
blocked_clients:0
# Use openredis.sh Store and query data
[[email protected]]# ./openredis.sh 6379 'set key1 v1 '
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
OK
[[email protected]]# ./openredis.sh 6379 'get key1 '
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
"v1"
# Use openredis.sh statistics
# Note that the package instructions are single quotation marks ,'--scan --pattern 'k*''
[[email protected]]# ./openredis.sh 6379 '--scan --pattern 'id:*'' | wc -l
66666
# Use openredis.sh Import data
# testdata.txt Deposit is A lot of “set key-0 value0” data
cat testdata.txt | ./openredis.sh 6379 --pipe
# Use openredis.sh Derived data
[[email protected]]# ./openredis.sh 6379 '--scan --pattern 'id:*'' > out.txt
66666
4.3、 Thinking questions :Linux Can I set the script to be executable but not readable
“ Password free connection Redis Script ” We mentioned , The password is saved in the script “openredis.sh” in , So we can take Ben “openredis.sh” Permission set to “ Executable but not readable ” Do you , In order to ensure the security of private information in the script .
# Set permissions to : The owner is readable, writable and executable ; Other users can only execute ;
chmod 711 openredis.sh
# redis Users have only executable rights
[[email protected]]$ ll openredis.sh
-rwx--x--x 1 root root 186 Nov 8 22:20 openredis.sh
[[email protected]]$ cat openredis.sh
cat: openredis.sh: Permission denied
[[email protected]]$ ./openredis.sh 6379 '--scan --pattern 'id:*'' | wc -l
bash: ./openredis.sh: Permission denied
0
From the above implementation , When the script is set to “ Executable but not readable ” when , The script is not executable , because “ The interpreter also needs to read the script ”.
The extension of knowledge :
If the permissions are set to “ Executable but not readable ” Is not a script , It's a binary file , At this point, the binary is executable .
# take JDK Of bin In the catalog java File set permissions to executable only , The actual discovery is executable ;
[[email protected] bin]$ ll java
---x--x--x 1 10 143 7734 Dec 13 2016 java
[[email protected] bin]$ java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
What are the ways that scripts can be implemented “ Executable but not readable ” Do you ? Welcome message discussion .
【 Get along well with Redis Series articles Recent highlights @zxiaofan】
《 Get along well with Redis- Two million were deleted key, Why memory is still not released ?》
《 Get along well with Redis-HyperLogLog Principle exploration 》
《 Get along well with Redis-HyperLogLog Statistics of daily life and monthly life of microblog 》
《 Get along well with Redis- How does Jingdong sign in for Jingdou 》
《 Get along well with Redis- The boss gives you a deep understanding of distributed locks 》