mysql导入redis
将mysql中数据库指定表导入redis
如何将mysql中某个数据库中的表数据快速导入redis?
以下将演示将本地127.0.0.1中数据库test中的表t_abc导入本地redis中。步骤如下:
1.建表语句:
CREATE TABLE `t_abc` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `orderNo` varchar(100) DEFAULT NULL, `createtime` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=131073 DEFAULT CHARSET=gbk
2.插入测试数据:
INSERT INTO `test`.`t_abc`(NAME,orderNo,createTime) VALUES ('zhangsan1','NO000001',NOW()); 执行多次以下sql,可以快速导入数据: INSERT t_abc(NAME,orderNo,createTime) SELECT t.name,t.orderNo,t.createTime FROM t_abc t;
3.mysql导入redis语句:
mysql -hlocalhost -uroot -proot -Dtest --default-character-set=utf8 --skip-column-names --raw <mysqltoredis.sql | redis-cli -h 127.0.0.1 -p 6379 -a 111111 –pipe
说明:
1.-h表示数据库地址,-u表示数据库用户名,-p表示数据库密码,-D表示哪个数据库
2. redis-cli -h 127.0.0.1 -p 6379 -a 111111 –pipe ,表示使用pipe管道连接redis
3.mysqltoredis.sql需要自己编写:
注意:1.因为RESP协议中的分隔符为在Linux下是\r\n,而在Windows下则为\n
2.第一行中的*10\n,10代表resp协议中数组的个数,\n表示换行符
3.在Linux下,最后变成了\r,而在Windows下就直接什么都没有了。
4.其中表t_abc为test数据库中的表,需要导入那列就查询哪列
在window中如下:
SELECT CONCAT( "*10\n", '$',LENGTH(redis_cmd),'\n',redis_cmd,'\n', '$',LENGTH(redis_key),'\n',redis_key,'\n', '$',LENGTH(hkey1),'\n',hkey1,'\n','$',LENGTH(hval1),'\n',hval1,'\n', '$',LENGTH(hkey2),'\n',hkey2,'\n','$',LENGTH(hval2),'\n',hval2,'\n', '$',LENGTH(hkey3),'\n',hkey3,'\n','$',LENGTH(hval3),'\n',hval3,'\n', '$',LENGTH(hkey4),'\n',hkey4,'\n','$',LENGTH(hval4),'\n',hval4 )FROM( SELECT 'HMSET' AS redis_cmd, CONCAT_WS(':','order', id) AS redis_key, 'id' AS hkey1, NAME AS hval1, 'name' AS hkey2, NAME AS hval2, 'orderNo' AS hkey3, orderNo AS hval3, 'createtime' AS hkey4, UNIX_TIMESTAMP(createtime) AS hval4 FROM t_abc )AS t
在linux中如下:
SELECT CONCAT( "*10\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\n', '$',LENGTH(hkey3),'\r\n',hkey3,'\r\n','$',LENGTH(hval3),'\r\n',hval3,'\r\n', '$',LENGTH(hkey4),'\r\n',hkey4,'\r\n','$',LENGTH(hval4),'\r\n',hval4,'\r' )FROM( SELECT 'HMSET' AS redis_cmd, CONCAT_WS(':','order', id) AS redis_key, 'id' AS hkey1, NAME AS hval1, 'name' AS hkey2, NAME AS hval2, 'orderNo' AS hkey3, orderNo AS hval3, 'createtime' AS hkey4, createtime AS hval4 FROM t_abc )AS t
4.常见问题:
ERR Protocol error: expected '$', got ' '
报这个错,需要检查第一行中*10\n 数字和数组的参数是否匹配