How to import, export and delete large amounts of data in redis production environment

zxiaofan666 2020-11-09 22:32:13
import export delete large amounts


《 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 ;
root@xxx:/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
[redis@xxx]$ 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 :password@host: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 
[redis@xxx 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 
[redis@redis]# ./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
[redis@redis]# ./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*''

[redis@redis]# ./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 

[redis@redis]# ./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 
[redis@redis]$ ll openredis.sh
-rwx--x--x 1 root root 186 Nov 8 22:20 openredis.sh
[redis@redis]$ cat openredis.sh
cat: openredis.sh: Permission denied
[redis@redis]$ ./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 ;
[admin@xxx bin]$ ll java
---x--x--x 1 10 143 7734 Dec 13 2016 java
[admin@xxx 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 》


Sweep yards attention 【 official account @zxiaofan】 Check out the latest article .
Life is all about choices!
In the future, you will be grateful for your hard work !
CSDN】【GitHub】【OSCHINA】【 Nuggets 】【 Language sparrow
【 WeChat official account 】

版权声明
本文为[zxiaofan666]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云