Skip to content

Repository files navigation

egg-cache

NPM versionbuild statusTest coverageDavid depsKnown Vulnerabilitiesnpm download

Based on cache-manager

All store engine based on cache-manager can be used.

中文文档

Installation

npm i egg-cache -S

or

yarn add egg-cache

Configuration

// config/plugin.jsexports.cache={enable: true,package: 'egg-cache',};
// config/config.default.jsexports.cache={default: 'memory',stores: {memory: {driver: 'memory',max: 100,ttl: 0,},},};

Usage

awaitapp.cache.set('foo','bar',60,{foo: 'bar'});awaitapp.cache.get('foo');// 'bar'awaitapp.cache.has('foo');// trueawaitapp.cache.del('foo');awaitapp.cache.get('foo','default');// 'default'awaitapp.cache.has('foo');// false// closureawaitapp.cache.set('foo',()=>{return'bar';});// 'bar'// Promiseawaitapp.cache.set('foo',()=>{returnPromise.resolve('bar');});// 'bar'// Get cached value. If it's not existed, get and save the value from closureawaitapp.cache.get('foo',()=>{return'bar';});// 'bar'// You can declare an `expire` optionawaitapp.cache.get('foo',()=>{return'bar';},60,{foo: 'bar'});// foo was cachedawaitapp.cache.get('foo');// 'bar'// clear cacheawaitapp.cache.reset();

Add store

  1. config: the store in the configuration uses the driver instead.
// config/config.default.jsconstredisStore=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-storedriver: redisStore,host: 'localhost',port: 6379,password: '',db: 0,ttl: 600,valid: _=>_!==null,},},};
  1. usage
conststore=app.cache.store('redis');awaitstore.set('foo','bar');awaitstore.get('foo');// 'bar'awaitstore.del('foo');awaitstore.has('foo');// false

Api

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.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.

License

MIT

About

💾 Cache plugin for eggjs

Topics

Resources

Stars

64 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages