将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下是 ,而在Windows下则为
2.第一行中的*10 ,10代表resp协议中数组的个数, 表示换行符
3.在Linux下,最后变成了 ,而在Windows下就直接什么都没有了。
4.其中表t_abc为test数据库中的表,需要导入那列就查询哪列
在window中如下:
SELECT CONCAT( "*10 ", '$',LENGTH(redis_cmd),' ',redis_cmd,' ', '$',LENGTH(redis_key),' ',redis_key,' ', '$',LENGTH(hkey1),' ',hkey1,' ','$',LENGTH(hval1),' ',hval1,' ', '$',LENGTH(hkey2),' ',hkey2,' ','$',LENGTH(hval2),' ',hval2,' ', '$',LENGTH(hkey3),' ',hkey3,' ','$',LENGTH(hval3),' ',hval3,' ', '$',LENGTH(hkey4),' ',hkey4,' ','$',LENGTH(hval4),' ',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 ", '$',LENGTH(redis_cmd),' ',redis_cmd,' ', '$',LENGTH(redis_key),' ',redis_key,' ', '$',LENGTH(hkey1),' ',hkey1,' ','$',LENGTH(hval1),' ',hval1,' ', '$',LENGTH(hkey2),' ',hkey2,' ','$',LENGTH(hval2),' ',hval2,' ', '$',LENGTH(hkey3),' ',hkey3,' ','$',LENGTH(hval3),' ',hval3,' ', '$',LENGTH(hkey4),' ',hkey4,' ','$',LENGTH(hval4),' ',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, createtime AS hval4 FROM t_abc )AS t
4.常见问题:
ERR Protocol error: expected '$', got ' '
报这个错,需要检查第一行中*10 数字和数组的参数是否匹配