小编给大家分享一下nodejs如何使用redis作为缓存介质实现封装缓存类,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
具体如下:
之前在node下使用redis作为缓存介质,对redis进行了一层封装
First: 安装npm包 redis
const redis = require('redis');
Second: 进行封装
// cache.js
const redis = require('redis');
const config = require('config');
const logger = require('winston');
const redisObj = {
client: null,
connect: function () {
this.client = redis.createClient(config.redis);
this.client.on('error', function (err) {
logger.error('redisCache Error ' + err);
});
this.client.on('ready', function () {
logger.info('redisCache connection succeed');
});
},
init: function () {
this.connect(); // 创建连接
const instance = this.client;
// 主要重写了一下三个方法。可以根据需要定义。
const get = instance.get;
const set = instance.set;
const setex = instance.setex;
instance.set = function (key, value, callback) {
if (value !== undefined) {
set.call(instance, key, JSON.stringify(value), callback);
}
};
instance.get = function (key, callback) {
get.call(instance, key, (err, val) => {
if (err) {
logger.warn('redis.get: ', key, err);
}
callback(null, JSON.parse(val));
});
};
// 可以不用传递expires参数。在config文件里进行配置。
instance.setex = function (key, value, callback) {
if (value !== undefined) {
setex.call(instance, key, config.cache.maxAge, JSON.stringify(value), callback);
}
};
return instance;
},
};
// 返回的是一个redis.client的实例
module.exports = redisObj.init();
How to use
const cache = require('./cache');
cache.get(key, (err, val) => {
if (val) {
// do something
} else {
// do otherthing
}
});
cache.set(key, val, (err, res) => {
// do something
});
cache.setex(key, val, (err, res) => {
// do something
})
以上是“nodejs如何使用redis作为缓存介质实现封装缓存类”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。