Cache
Midway Cache is a component that facilitates developers to perform caching operations, and it is beneficial to improve the performance of the project. It provides us with a data center for efficient data access.
Related information:
| Description | |
|---|---|
| Can be used for standard projects | ✅ |
| Can be used for Serverless | ✅ |
| Can be used for integration | ✅ |
| Contains independent main framework | ❌ |
| Contains independent logs | ❌ |
Installation
First install the relevant component modules.
$ npm i @midwayjs/cache@4 cache-manager --save
$ npm i @types/cache-manager --save-dev
Or reinstall the following dependencies in package.json.
{
"dependencies": {
"@midwayjs/cache": "^4.0.0",
"cache-manager": "^3.4.1 ",
// ...
},
"devDependencies": {
"@types/cache-manager": "^3.4.0 ",
// ...
}
}
Use Cache
Midway provides a unified API for different cache stores. By default, a data center based on memory data storage is built in. If you want to use another data center, developers can also switch to modes such as mongodb and fs.
First, the Cache component is introduced and imported in the configuration.ts:
import { Configuration, App } from '@midwayjs/core';
import * as cache from '@midwayjs/cache';
import { join } from 'path'
@Configuration({
imports: [
// ...
cache // import cache component
],
importConfigs: [
join(__dirname, 'config')
]
})
export class MainConfiguration {
}
It can then be injected into the business code.
import { Inject, Provide } from '@midwayjs/core';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cacheManager: CacheManager; // inject CacheManager
}
Set through the provided API to obtain cached data.
import { Inject, Provide } from '@midwayjs/core';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cacheManager: CacheManager;
async getUser(options: IUserOptions) {
// Set cache content
await this.cacheManager.set('name', 'stone-jin');
// Get cached content
let result = await this.cacheManager.get('name');
return result;
}
async getUser2() {
// Get cached content
let result = await this.cacheManager.get('name');
return result;
}
async reset() {
Await this.cacheManager.reset(); // Clear the contents of the corresponding store
}
}
Set cache
You can use the await this.cache.set(key, value) method to set this parameter. The default expiration time is 10s.
You can also manually set TTL (Expiration Time), as follows:
Await this.cacheManager.set(key, value, {ttl: 1000}); // ttl is in seconds
If you don't want to Cache expired, set TTL to null.
await this.cacheManager.set(key, value, {ttl: null});
At the same time, you can also set it through the global config.default.ts.
export default {
// ...
cache: {
store: 'memory',
options: {
max: 100
Ttl: 10, // Modify the default ttl configuration
},
}
}