使用ioredis
安装
$ npm install ioredis -D
初始化redis
import Redis from 'ioredis';
export const REDIS_DB_0 = new Redis({
port: 6379, // Redis port
host: '127.0.0.1', // Redis host
// family: 4, // 4 (IPv4) or 6 (IPv6)
name: 'person',
password: '',
db: 0,
});
export const REDIS_DB_1 = new Redis({
port: 6379, // Redis port
host: '127.0.0.1', // Redis host
// family: 4, // 4 (IPv4) or 6 (IPv6)
name: 'user',
password: '',
db: 1,
});
使用redis
@Get('redis')
@HttpCode(HttpStatus.OK)
async testRedis() {
await REDIS_DB_0.set(
'person',
JSON.stringify({
name: 'amin',
age: 16,
hobby: ['study', 'sport'],
character: 'cool',
}),
);
const person = JSON.parse(await REDIS_DB_0.get('person'));
await REDIS_DB_1.set(
'user',
JSON.stringify({
name: 'mengyajiao',
age: 18,
hobby: ['study', 'sport'],
character: 'beautiful',
}),
);
const user = JSON.parse(await REDIS_DB_1.get('user'));
return [person, user];
}
效果展示