2015-11-05 149 views
0

我需要每15分钟将数据从MySQL数据库同步到Redis缓存,以便将缓存作为最新数据。每15分钟刷新Azure Redis缓存

我使用Ubuntu的托管(Node.js)webservcies。因此,每次都需要调用rest API,以便从缓存中获取数据并提供服务。

所以现在我需要写一个后台作业来同步MySQL数据到缓存内存。

如果我需要编写后台作业,我可以在node.js中编写并使用crontab命令将其同步并在Ubuntu中作为后台作业运行。

回答

2

是的。您可以编写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 
+0

感谢彼得... – Sharath