Cache plugin for Egg, fork from egg-cache
npm install egg-cachexsh
npm i egg-cachex -S
`
or
`sh
yarn add egg-cachex
`
Configuration
`js
// config/plugin.js
exports.cache = {
enable: true,
package: 'egg-cachex',
};
`
`js
// config/config.default.js
exports.cache = {
default: 'memory',
stores: {
memory: {
driver: 'memory',
max: 100,
ttl: 0,
},
},
};
`
Usage
`js
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();
`
$3
1. config: the store in the configuration uses the driver instead.
`js
// 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,
},
},
};
`
2. usage
`js
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
`
$3
#### cache.set(name, value, [expire=null, options=null]);
Set Cache
- name cache name
- value cache value
- expire (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
`sh
npm test
``