在express項目中使用redis


在express項目中使用redis

准備工作

  • 安裝redis

  • 安裝redis桌面管理工具:Redis Desktop Manager

  • 項目中安裝redis:npm install redis

開始使用redis

使用方法很簡單,初始化redis后,就可以使用了,如下:

//初始化
var redis = require("redis"),
client = redis.createClient();

client.on("error", function (err) {
console.log("Error " + err);
});


//使用
client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
console.log(replies.length + " replies:");
replies.forEach(function (reply, i) {
console.log(" " + i + ": " + reply);
});
client.quit();
});
 

在項目中使用redis

如果在項目中使用redis,我們希望初始化一次,處處可用。我們如何讓初始化后的redisClient成為全局變量,或者在別的模塊中可用呢。

方法一:將redisClient存儲在node的全局對象global中

在 ./bin/www 中創建client,並保存在全局對象global中:

global.redisClient = require("redis").createClient();

這樣,redisClient在各模塊中,不用引用,到處可用。

在controller層,需要使用redisClient的地方,直接使用

redisClient.hmset("user:"+uid ,{uid:uid,name:"wuwanyu",age:"21"},next);

方法二: 將redis初始化方法,封裝在index.js中,然后exports出去

exports.init = function(){
var configs = require('../config.json');

var redis = require("redis"),
redisClient = redis.createClient(configs.redis);

redisClient.on("error", function (err) {
console.log("Error " + err);
});

return redisClient;
};

使用時:

var redisClient = require("../database/index.js").init();
redisClient.hgetall("user:"+uid,next);

方法三:將init,close,hmset,hgetall封裝方法

初始化redis:

// database/redis.js
module.init = function(callback) {

redisClient = redis.createClient(configs.redis);


require('./redis/main')(redisClient, module);
require('./redis/hash')(redisClient, module);
require('./redis/sets')(redisClient, module);
require('./redis/sorted')(redisClient, module);
require('./redis/list')(redisClient, module);

module.redisClient = redisClient;

if(typeof callback === 'function') {
callback();
}
};
 

封裝redis的hmset,hgetall等方法:

// database/redis/hash

"use strict";

module.exports = function(redisClient, module) {

var helpers = module.helpers.redis;

module.setObject = function(key, data, callback) {
callback = callback || function() {};
redisClient.hmset(key, data, function(err) {
callback(err);
});
};


module.getObject = function(key, callback) {
redisClient.hgetall(key, callback);
};
};
 
 

在./bin/www 調用redis.init()方法,初始化redis;

async.waterfall([
function(cb){
redis.init(cb); //初始化redis
},
],function(){
// 啟動node
});
 

在各個controller內調用:

var redis = require("../database/redis.js");

redis.setObject("user:"+uid ,{uid:uid,name:"wuwanyu",age:"21"},next);
redis.getObject("user:"+uid,next);
 
目錄結構:
 
項目地址:
https://github.com/wuwanyu/redis.express.test


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM