Skip to content

hexindai/egg-cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

egg-cache

NPM version build status Test coverage David deps Known Vulnerabilities npm 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.js
exports.cache = {
  enable: true,
  package: 'egg-cache',
};
// 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.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();

Add store

  1. config: the store in the configuration uses the driver 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,
    },
  },
};
  1. 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 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