欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

如何向redis中写入大量的数据

2025年08月06日 Redis
1.编写python脚本,生成redis命令redis_info.py#!/usr/bin/pythonfor i in range(5000000): #循环的数量 print 'se

1.编写python脚本,生成redis命令

  • redis_info.py
#!/usr/bin/python
for i in range(5000000): #循环的数量
        print 'set name'+str(i),'hello'+str(i) #str(i)将int类型转换为str类型,否则不能进行字符串拼接

2.运行python脚本输出到redis_comm.txt文件中

python redis_info.py > redis_comm.txt
  • 生成一个redis_comm.txt文件
head -n 10 redis_comm.txt 
set name0 hello0
set name1 hello1
set name2 hello2
set name3 hello3
set name4 hello4
set name5 hello5
set name6 hello6
set name7 hello7
set name8 hello8
set name9 hello9

3.将redis命令生成redis protocol

编写脚本redis_data.sh

  • #!/bin/bash
while read cmd; do
  # each command begins with *{number arguments in command}

  xs=($cmd); printf "*${#xs[@]}
"
  # for each argument, we append ${length}
{argument}

  for x in $cmd; do printf "$${#x}
$x
"; done
done < redis_comm.txt

4.运行shell脚本

sh redis_data.sh > redis_data.txt
head -n 10 redis_data.txt 
*3
$3
set
$5
name0
$6
hello0
*3
$3
set

5.管道(pipeline)就是为了改善这个情况的

利用管道技术,客户端可以一次性发送多个请求而不用等待服务器的响应,待所有命令都发送完后再一次性读取服务的响应。

 cat redis_data.txt |redis-cli -h 192.168.102.95 --pipe

直接就可以运行了

6.验证,去查看数据是否插入成功

info查看

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。