super-cache
Node.js缓存管理模块,支持自定义存储引擎
在Node.js中使用
1、安装
$ npm install super-cache --save
2、载入模块
var SuperCache = ;var cache = ttl: 60;
在浏览器中使用
可供在浏览器上使用的文件存放在dist
目录
1、Shim方式
2、AMD方式
入门
var cache = ttl: 60; // 定义缓存date的数据如何获取cache; // 取缓存,如果缓存不存在则会先调用已设置的方法来获取cache;
详细使用方法
1、创建SuperCache
实例:
var cache = // 存储引擎 store: // 缓存有效期,单位:秒 ttl: 60;
2、定义获取缓存的方法:
// 定义获取缓存key的方法cache; // key可以是一个正则表达式,或者是一个函数(返回true/fase)// 当查找没有匹配的字符串key时,则会依次判断正则表达式或者函数的key// 所以此类key数量不宜过多cache;cache;
3、查询缓存:
// 获取缓存,如果缓存不存在则先执行预设的方法取得缓存再返回cache;
4、查询临时的缓存:
// 获取缓存,如果缓存不存在则使用当前设置的方法取得缓存再返回cache;
5、设置缓存:
// 设置缓存,如果没有指定ttl则使用默认的ttl// 回调函数可选cache;
6、删除缓存:
// 设置缓存,如果没有指定ttl则使用默认的ttl// 回调函数可选cache;
内置的存储引擎
使用内置的存储引擎可以设置store
为一个字符串,比如:
var cache = // 存储引擎 store: 'memory' // 存储引擎的初始化参数 storeConfig: max: 1000 gcProbability: 001 // 缓存有效期,单位:秒 ttl: 60;
内置存储引擎包括memory
,redis
,memcache
,local
。
1、Memory存储引擎
// max为最大key数量var store = max: 1000 // 最大key数量 gcProbability: 001 // 执行GC的几率,0.01表示1%;
2、Redis存储引擎(仅Node.js中使用)
var store = host: '127.0.0.1' // 服务器地址 port: 6379 // 服务器端口 db: 0 // 数据库号码 prefix: 'cache:' // key前缀 password: 'xxx' // 密码 pool: 1 // 连接池数量;
3、Memchache存储引擎(仅Node.js中使用)
var store = host: '127.0.0.1' // 服务器地址 port: 11211 // 服务器端口 prefix: 'cache:' // key前缀 user: 'xxx' // 用户名 password: 'xxx' // 密码 pool: 1 // 连接池数量;
4、localStorage/sessionStorage存储引擎(仅浏览器中使用)
// max为最大key数量var store = type: 'local' // 类型,local=localStorage, session=sessionStorage, 默认local prefix: 'cache_' // key前缀,默认cache_ path: './data' // 数据存储路径,仅Node.js中使用时需要指定 max: 1000 // 最大key数量,默认1000 gcProbability: 001 // 执行GC的几率,0.01表示1%;
自定义存储引擎
存储引擎需要实现以下接口:
var store = {}; // 取缓存store { // name为缓存名称 // 此处查询数据库,再调用callback返回数据 // 若data为undefined或null表示该缓存不存在 ;}; // 设置缓存store { // name为缓存名称 // data为缓存数据 // ttl为缓存有效期 // 设置完缓存后,再调用callback返回 ;}; // 删除缓存store { // name为缓存名称 // 删除完缓存后,再调用callback返回};
License
The MIT License (MIT)
Copyright (c) 2015-2016 SuperID | 一切只为简单登录
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.