本文實(shí)例講述了nodejs使用redis作為緩存介質(zhì)實(shí)現(xiàn)的封裝緩存類(lèi)。分享給大家供大家參考,具體如下:
之前在node下使用redis作為緩存介質(zhì),對(duì)redis進(jìn)行了一層封裝
First: 安裝npm包 redis
const redis = require('redis');Second: 進(jìn)行封裝
// cache.jsconst 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(); // 創(chuàng)建連接 const instance = this.client; // 主要重寫(xiě)了一下三個(gè)方法。可以根據(jù)需要定義。 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參數(shù)。在config文件里進(jìn)行配置。 instance.setex = function (key, value, callback) { if (value !== undefined) { setex.call(instance, key, config.cache.maxAge, JSON.stringify(value), callback); } }; return instance; },};// 返回的是一個(gè)redis.client的實(shí)例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})希望本文所述對(duì)大家nodejs程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注