redis批量导入数据

一、采用redis 管道 --pipe

1、先生成文本数据 redis.txt 的 文件格式

有两种文件格式 都是可以的(以下采用的是redis 的hash村粗怒)

*6
$5
hmset
$24
user_profile:user_info:0
$4
name
$3
317
$3
age
$3
187

解释:

*6 表示有三个字符  

$5 表示 hmset字符长度为5 也就是我们的命令

$24表示 user_profile:user_info:0的长度为24 也就是我们的key

以此类推

格式二:

hmset user_profile:user_info:0 name 张三 age 12
hmset user_profile:user_info:0 name 李四 age 13

2、文件格式

[atguigu@hadoop105 ~] unix2dos redis.txt

上面的命令会去掉行尾的^M符号

3、执行命令

[atguigu@hadoop105 ~] cat redis.txt | ./redis-cli -h 127.0.0.1 -a password - p 6379 --pipe

遇到的坑

1: 没有 unix2dos 命令

yum install unix2dos 

二、采用Java api 方式

@Test
    public void importRedis(){
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //管道
        Pipeline pipe = jedis.pipelined();

        for (int i=0;i<1000000;i++){
            Map<String, String> map = new HashMap<>();
            map.put("name", "张三");
            map.put("age","12");
            pipe.hmset("user_profile:user_info:"+i, map);
        }
        // 执行命令
        pipe.sync();
        jedis.close();
    }

三、批量删除key

[atguigu@hadoop105 ~] ./redis-cli -h 127.0.0.1 -p 6379 KEYS "user_profile*" | xargs ./redis-cli -h 127.0.0.1 -p 6379 DEL