Based on cache-manager
All store engine based on cache-manager can be used.
npm i egg-cache -S
or
yarn add egg-cache
// config/plugin.js
exports.cache = {
enable: true,
package: 'egg-cache',
};
// config/config.default.js
exports.cache = {
default: 'memory',
stores: {
memory: {
driver: 'memory',
max: 100,
ttl: 0,
},
},
};
await app.cache.set('foo', 'bar', 60, { foo: 'bar' });
await app.cache.get('foo'); // 'bar'
await app.cache.has('foo'); // true
await app.cache.del('foo');
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();
- 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
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)
Refer to config/config.default.js
npm test
Refer to Issues.