首页 > 编程 > JavaScript > 正文

nodejs使用redis作为缓存介质实现的封装缓存类示例

2019-11-19 14:23:49
字体:
来源:转载
供稿:网友

本文实例讲述了nodejs使用redis作为缓存介质实现的封装缓存类。分享给大家供大家参考,具体如下:

之前在node下使用redis作为缓存介质,对redis进行了一层封装

First: 安装npm包 redis

const redis = require('redis');

Second: 进行封装

// 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(); // 创建连接    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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表