美文网首页
nodejs访问redis时的key helper封装

nodejs访问redis时的key helper封装

作者: tpglzu | 来源:发表于2016-07-26 14:26 被阅读0次

前言

key helper主要负责以下内容

  • 定义redis访问时所需要的所有keypattern
  • 提供从key pattern中获取实际key的函数
    如从'0x90:user:#userID#:score:#corseID#''0x90:user:0001:score:01'
  • 提供了从指定key pattern中获取指定字段的值

定义key pattern

module.exports = {
  master: 'master',
  user: {
    count: '0x01:user:total',
    name: '0x01:user:#userID#',
    score: *'0x90:user:#userID#:score:#corseID#'
    getUserId: function(name) {
      return name.split(':')[2];
    },
    getCorseId: function(score) {
      return score.split(':')[4];
    },
  }
  // 省略
}

定义key pattern的转换函数

module.exports = {
  // 省略
  getKey: function(key, json) {
    var params = key.match(/#.*?#/g);
    params.forEach(function(param, index) {
      var jsonKey = param.replace(/#/g, '');
      if (json[jsonKey] === undefined) {
        throw new Error('Invalid redis key...KEY:' + key + ' PARAMS:' +
          json);
      }
      key = key.replace(param, json[jsonKey]);
    });
    return key;
  }
}

调用方法

var keyHelper = require('./keyHelper');
var key = keyHelper.getKey(keyHelper.user.score, {
          userID: 0001,
          corseID: 01
        })
// redis访问处理略

完整代码如下

// keyHelper.js
module.exports = {
  master: 'master',
  user: {
    count: '0x01:user:total',
    name: '0x01:user:#userID#',
    score: *'0x90:user:#userID#:score:#corseID#'
    getUserId: function(name) {
      return name.split(':')[2];
    },
    getCorseId: function(score) {
      return score.split(':')[4];
    },
  }
  getKey: function(key, json) {
    var params = key.match(/#.*?#/g);
    params.forEach(function(param, index) {
      var jsonKey = param.replace(/#/g, '');
      if (json[jsonKey] === undefined) {
        throw new Error('Invalid redis key...KEY:' + key + ' PARAMS:' +
          json);
      }
      key = key.replace(param, json[jsonKey]);
    });
    return key;
  }
}

相关文章

网友评论

      本文标题:nodejs访问redis时的key helper封装

      本文链接:https://www.haomeiwen.com/subject/jdvnjttx.html