Cache Types

The module a-cache provides three types of caching:

  1. Memory Cache: valid only for the current process
  2. Database Cache:can be used across processes/machines
  3. Redis Cache:can be used across processes/machines

Database Cache == Redis Cache

In order to maintain downward compatibility of the system, by default, Database Cache is Redis Cache. The related config parameters of module a-cache are as follows:

a-cache/backend/src/config/config.js

  // db
  config.db = {
    redis: true,
  };

Memory Cache

Module a-cache injects object cache.mem into ctx through middleware mechanism

src/module/test-party/backend/src/controller/test/cache/mem.js

set

// set(name, value, timeout)
this.ctx.cache.mem.set('name', 'zhennann', 1000);
Name Default Description
name cache name
value cache value
timeout 0 cache timeout

has

let res = this.ctx.cache.mem.has('name');

get

let value = this.ctx.cache.mem.get('name');

remove

this.ctx.cache.mem.remove('name');

Across Module

Access to the cache defined by other modules

// other module's cache
const moduleCache = this.ctx.cache.mem.module('test-party');
// get
let value = moduleCache.get('name');

Database Cache

Module a-cache injects object cache.db into ctx through middleware mechanism

src/module/test-party/backend/src/controller/test/cache/db.js

set

// set(name, value, timeout)
await this.ctx.cache.db.set('name', 'zhennann', 1000);
Name Default Description
name cache name
value cache value
timeout 0 cache timeout

has

let res = await this.ctx.cache.db.has('name');

get

let value = await this.ctx.cache.db.get('name');

remove

await this.ctx.cache.db.remove('name');

Across Module

Access to the cache defined by other modules

// other module's cache
const moduleCache = this.ctx.cache.db.module('test-party');
let value = await moduleCache.get('name');

Redis Cache

Module a-cache injects object cache.redis into ctx through middleware mechanism

src/module/test-party/backend/src/controller/test/cache/redis.js

set

// set(name, value, timeout)
await this.ctx.cache.redis.set('name', 'zhennann', 1000);
Name Default Description
name cache name
value cache value
timeout 0 cache timeout

has

let res = await this.ctx.cache.redis.has('name');

get

let value = await this.ctx.cache.redis.get('name');

remove

await this.ctx.cache.redis.remove('name');

Across Module

Access to the cache defined by other modules

// other module's cache
const moduleCache = this.ctx.cache.redis.module('test-party');
let value = await moduleCache.get('name');