每15分钟刷新一次Azure Redis缓存

时间:2015-11-05 02:05:34

标签: mysql node.js azure redis

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

我正在使用ubuntu来托管(Node.js)webservcies。因此,每当有呼叫休息api时,它需要从缓存中获取数据并提供服务。

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

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

1 个答案:

答案 0 :(得分:2)

是。您可以编写nodejs脚本并通过crontab命令运行它以将数据从MySQL同步到Redis。

根据我的经验,您需要下面的一些nodejs包来帮助实现这些需求。

MySQL的NodeJS ORM:

NodeJS的Redis客户端:

示例代码~/sync-mysql-redis.js

// Create a mysql client connection
var Sequelize = require('sequelize');
var sequelize = new Sequelize('mysql://user:pass@azure_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配置,您需要以root用户身份或sudo用户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