1.
新建一个文本文件,包含redis命令
SET
Key0
Value0
SET
Key1
Value1
...
SET
KeyN
ValueN
如果有了原始数据,其实构造这个文件并不难,譬如shell,python都可以
2.
将这些命令转化成Redis
Protocol。
因为Redis管道功能支持的是Redis
Protocol,而不是直接的Redis命令。
如何转化,可参考后面的脚本。
3.
利用管道插入
cat
data.txt
|
redis-cli
--pipe
Shell
VS
Redis
pipe
下面通过测试来具体看看Shell批量导入和Redis
pipe之间的效率。
测试思路:分别通过shell脚本和Redis
pipe向数据库中插入10万相同数据,查看各自所花费的时间。
Shell
脚本如下:
#!/bin/bash
for
((i=0i<100000i++))
do
echo
-en
"helloworld"
|
redis-cli
-x
set
name$i
>>redis.log
done
每次插入的值都是helloworld,但键不同,name0,name1...name99999。
Redis
pipe
Redis
pipe会稍微麻烦一点
1>
首先构造redis命令的文本文件
在这里,我选用了python
#!/usr/bin/python
for
i
in
range(100000):
'set
name'+str(i),'helloworld'
#
python
1.py
>
redis_commands.txt
#
head
-2
redis_commands.txt
set
name0
helloworld
set
name1
helloworld
2>
将这些命令转化成Redis
Protocol
在这里,我利用了github上一个shell脚本,
#!/bin/bash
while
read
CMD
do
#
each
command
begins
with
*{number
arguments
in
command}\r\n
XS=($CMD)
printf
"*${#XS[@]}\r\n"
#
for
each
argument,
we
append
${length}\r\n{argument}\r\n
for
X
in
$CMD
do
printf
"\$${#X}\r\n$X\r\n"
done
done
<
redis_commands.txt
#
sh
20.sh
>
redis_data.txt
#
head
-7
redis_data.txt
*3
$3
set
$5
name0
$10
helloworld
至此,数据构造完毕。
测试结果
需要确保已经安装了 redis 服务及 Java redis 驱动(jedis.jar)import redis.clients.jedis.Jedis
public class RedisStringJava {
public static void main(String[] args) {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost")
System.out.println("连接成功")
//设置 redis 字符串数据
jedis.set("str", "字符串")
// 获取存储的数据并输出
System.out.println("redis 存储的字符串为: "+ jedis.get("str"))
}}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)