mysql数据批量写入redis中,方法倒是有很多种!效率最高的就是通过redis-cl管道的方式写入。

# 命令

cat redis.txt | redis-cli -h 127.0.0.1 -a password - p 6379 --pipe
1

结构很简单 redis.txt 是你的文件名称 后面是你的客户端

# 文件格式

演示数据表

CREATE TABLE `mobiles` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `mobile` char(11) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '手机号',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
1
2
3
4
5

生成 redis.txt 文件

    SELECT CONCAT(  
       "*6\r\n",  
       '$',LENGTH(redis_cmd),'\r\n',redis_cmd,'\r\n',  
       '$',LENGTH(redis_key),'\r\n',redis_key,'\r\n',  
       '$',LENGTH(hkey1),'\r\n',hkey1,'\r\n','$',LENGTH(hval1),'\r\n',hval1,'\r\n',  
       '$',LENGTH(hkey2),'\r\n',hkey2,'\r\n','$',LENGTH(hval2),'\r\n',hval2,'\r'
    ) 
	FROM(  
       SELECT 'HMSET' AS redis_cmd,  
       concat_ws(':','person', id) AS redis_key,  
       'id' AS hkey1, id AS hval1,  
       'mobile' AS hkey2, mobile AS hval2
       From mobiles
    )AS t  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
*6
$5
HMSET
$8
person:1
$2
id
$1
1
$6
mobile
$11
130****8480
1
2
3
4
5
6
7
8
9
10
11
12
13

解释:

*6 表示有6个元素
$5 表示 `HMSET` 字符长度为5
$8 表示 `person:1` 字符长度为8
$2 表示 `id` 字符长度为2
$1 表示 `1` 字符长度为1
$6 表示 `mobile` 字符长度为6
$11 表示 `130****8480` 字符长度为11
1
2
3
4
5
6
7

# 转码

unix2dos  redis.txt 
1

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

# 结果

[root@zjwoo ~]# cat 1.sql |redis-cli -p 16379 -a 7G***lh --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: 146344
1
2
3
4
5

集群模式下会有 MOVEN *** 错误,可以使用

  1. 如果不通过 pipe 我们可以通过 redis-cli -c 来启动redis集群模式。
  2. 可以去集群的每个节点跑 --pipe 一次,那么每个节点 就会写入自己的数据
  3. 通过key的哈希值 区分槽点,通过节点拿到槽点