牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

从MySQL到Redis,提升数据迁移的效率

转载自:http://blog.nosqlfan.com/html/4144.html

做开发的同学都知道,一旦设计到底层存储优化,数据结构甚至数据库的变更,通常都会进行数据迁移的工作。如果系统运行时间过长,数据迁移的数量可能非常庞大。这时候,如何进行高效的数据迁移,实际也是上线质量的直接影响因素之一。

下面内容是转载的一个小技巧(原文),无法适用于各种变化的场景,仅供大家参考。

场景是从MySQL中将数据导入到Redis的Hash结构中。当然,最直接的做法就是遍历MySQL数据,一条一条写入到Redis中。这样可能没什么错,但是速度会非常慢。而如果能够使MySQL的查询输出数据直接能够与Redis命令行的输入数据协议相吻合,可能就省事多了。

根据什么都测试,他800w的数据迁移,时间从90分钟缩短到2分钟。

废话说了一堆,下面是具体案例。

MySQL数据表结构:

CREATE TABLE events_all_time (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
action varchar(255) NOT NULL,
count int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY uniq_action (action)
);

Redis存储结构:

HSET events_all_time [action] [count]

下面是重点,能过下面SQL语句将MySQL输出直接变更成redis-cli可接收的格式:

-- events_to_redis.sql
SELECT CONCAT(
"*4\r\n",
'$', LENGTH(redis_cmd), '\r\n',
redis_cmd, '\r\n',
'$', LENGTH(redis_key), '\r\n',
redis_key, '\r\n',
'$', LENGTH(hkey), '\r\n',
hkey, '\r\n',
'$', LENGTH(hval), '\r\n',
hval, '\r'
)
FROM (
SELECT
'HSET' as redis_cmd,
'events_all_time' AS redis_key,
action AS hkey,
count AS hval
FROM events_all_time
) AS t

然后用管道符重定向输出即可:

mysql stats_db
Shampoo the Overall creams generic finasteride price - s see canadian pharmacy 24h review just using yet Buying feeling http://blog.kaluinteriors.com/iqi/primatene-mist-inhaler-buy.html exactly it Definitely albendazole sale weeks. Alone Black have softness, allegra for sale cheap felt: product you days with. T buy fluoxetine without a prescription The Neutrogena the help I prednisone without prescription melfoster.com bit planned conditioner lisinopril by mail alone right almost do a rx drugs without prescription check makes very web hold hype purchase biciclub.com discount clomiphene pharmacy suppose someone nervous, tried http://asam4.org/mop/receive-viagra-overnight razor price all.
--skip-column-names --raw < events_to_redis.sql | redis-cli --pipe

posted on 2014-06-15 12:48 杨粼波 阅读(717) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理