是的。您可以编写nodejs脚本并通过crontab命令运行它,以将MySQL中的数据同步到Redis。
根据我的经验,您需要下面的一些nodejs包来帮助实现需求。
的NodeJS ORM为MySQL:
的Redis客户端的NodeJS:
示例代码~/sync-mysql-redis.js
:
// Create a mysql client connection
var Sequelize = require('sequelize');
var sequelize = new Sequelize('mysql://user:[email protected]_mysql_host:3306/dbname');
// Create a redis client using node_redis
var redis = require("redis");
var client = redis.createClient(6379, '<redis_host>');
// Query entities data from MySQL table
sequelize.query("SELECT * FROM `t_entity`", { type: sequelize.QueryTypes.SELECT})
.then(function(entities) {
for(var entity in entites) { // for-each entity from entites list
var hash_key = entity.Id // for example, get the entity id as redis hash
for(var prop in entity) { // for-each property from entity
client.hset([hash_key, prop, entity[prop]], redis.print); // mapping a mysql table record to a redis hash
}
}
});
对于crontab的配置,则需要VIM/etc/crontab中作为根或须藤用户:
$ sudo vim /etc/crontab
# Add a crontab record to run nodejs script interval 15 mins
*/15 * * * * node \home\user\sync-mysql-redis.js
感谢彼得... – Sharath