egg-cachex
v0.0.9
Published
Cache plugin for Egg, fork from egg-cache
Downloads
3
Maintainers
Readme
egg-cachex
Based on cache-manager
All store engine based on cache-manager can be used.
Installation
npm i egg-cachex -S
or
yarn add egg-cachex
Configuration
// config/plugin.js
exports.cache = {
enable: true,
package: 'egg-cachex',
};
// config/config.default.js
exports.cache = {
default: 'memory',
stores: {
memory: {
driver: 'memory',
max: 100,
ttl: 0,
},
},
};
Usage
await app.cache.set('foo', 'bar', 60, { foo: 'bar' });
await app.cache.set('foo1', 'bar1', 60, { foo: 'bar' });
await app.cache.get('foo'); // 'bar'
await app.cache.has('foo'); // true
await app.cache.del('foo');
await app.cache.mdel(['foo','foo1']);
await app.cache.get('foo', 'default'); // 'default'
await app.cache.has('foo'); // false
// closure
await app.cache.set('foo', () => {
return 'bar';
}); // 'bar'
// Promise
await app.cache.set('foo', () => {
return Promise.resolve('bar');
}); // 'bar'
// Get cached value. If it's not existed, get and save the value from closure
await app.cache.get('foo', () => {
return 'bar';
}); // 'bar'
// You can declare an `expire` option
await app.cache.get('foo', () => {
return 'bar';
}, 60, {
foo: 'bar'
});
// foo was cached
await app.cache.get('foo'); // 'bar'
// clear cache
await app.cache.reset();
Add store
- config: the
store
in the configuration uses thedriver
instead.
// config/config.default.js
const redisStore = require('cache-manager-ioredis');
exports.cache = {
default: 'memory',
stores: {
memory: {
driver: 'memory',
max: 100,
ttl: 0,
},
redis: { // full config: https://github.com/dabroek/node-cache-manager-ioredis#single-store
driver: redisStore,
host: 'localhost',
port: 6379,
password: '',
db: 0,
ttl: 600,
valid: _ => _ !== null,
},
},
};
- usage
const store = app.cache.store('redis');
await store.set('foo', 'bar');
await store.get('foo'); // 'bar'
await store.del('foo');
await store.has('foo'); // false
Api
cache.set(name, value, [expire=null, options=null]);
Set Cache
name
cache namevalue
cache valueexpire
(Optional) expire(default from config file,the unit is second,0
means nerver expire)options
(Optional) Refer to cache-manager)
cache.get(name, [defaultValue=null, expire=null, options=null]);
cache.del(name);
cache.mdel([name,name1]);
cache.has(name);
cache.store(name, [options=null]);
cache.reset();
Default configuration
Refer to config/config.default.js
Unit Test
npm test
Issue
Refer to Issues.