Redis(ioredis) module for Nest framework (node.js) 🚀
$ npm i --save @jasonsoft/nestjs-redis ioredis
Import RedisModule
:
@Module({
imports: [
RedisModule.forRoot({
url: 'redis://username:password@localhost:6379',
}),
],
providers: [...],
})
export class AppModule {}
@Module({
imports: [
RedisModule.forRoot({
port: 6379, // Redis port
host: 'localhost', // Redis host
username: 'default', // needs Redis >= 6
password: 'password',
db: 0, // Defaults to 0
}),
],
providers: [...],
})
export class AppModule {}
Inject RedisCacheHelper
:
@Injectable()
export class AppService {
constructor(private readonly redisCacheHelper: RedisCacheHelper) {}
}
Quite often you might want to asynchronously pass your module options instead of passing them beforehand. In such case, use forRootAsync()
method.
RedisModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
url: configService.get('REDIS_URL'),
}),
inject: [ConfigService],
}),
import { RedisCacheHelper } from '@jasonsoft/nestjs-redis';
import { Injectable } from '@nestjs/common';
export interface User {
id: number;
name: string;
age: number;
}
export const USERS: User[] = [
{
id: 1,
name: 'Jason Song',
age: 18,
},
{
id: 2,
name: '成长的小猪',
age: 30,
},
];
@Injectable()
export class AppService {
constructor(private readonly redisCacheHelper: RedisCacheHelper) {}
async getUser(id: number): Promise<User> {
const cacheKey = `user:${id}`;
let user = await this.redisCacheHelper.getAsObj<User>(cacheKey);
if (!user) {
user = USERS.find((user) => user.id === id);
if (user) {
await this.redisCacheHelper.set(cacheKey, user);
}
}
return user;
}
async commonOperation() {
/** string type */
await this.redisCacheHelper.set('string:type', 'test', 60);
const stringValue = await this.redisCacheHelper.getAsStr('string:type');
/** number type */
await this.redisCacheHelper.set('number:type', 1, '30m');
const numberValue = await this.redisCacheHelper.getAsNum('number:type');
/** boolean type */
await this.redisCacheHelper.set('boolean:type', true, '8h');
const booleanValue = await this.redisCacheHelper.getAsBool('boolean:type');
/** object:type */
const user = USERS.find((user) => user.name === 'Jason Song');
await this.redisCacheHelper.set('object:type', user, '7d');
const objectValue = await this.redisCacheHelper.getAsObj<User>(
'object:type',
);
}
}
To use ioredis built-in usage
/** Import `InjectRedis` and `Redis` from `@jasonsoft/nestjs-redis` */
import { InjectRedis, Redis } from '@jasonsoft/nestjs-redis';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
/** The @InjectRedis() decorator provides injection into Redis */
constructor(@InjectRedis() private readonly redis: Redis) {}
async getUser(): Promise<string> {
const names = ['jason', 'jasonsoft', '成长的小猪'];
await this.redis.lpush('names', ...names);
return await this.redis.lpop('names');
}
/** ioredis basic usage */
async basicUsage() {
await this.redis.set('mykey', 'value');
let result = await this.redis.get('mykey');
console.log(result); // Prints "value"
result = await this.redis.get('mykey');
console.log(result); // Prints "value"
await this.redis.zadd(
'sortedSet',
1,
'one',
2,
'dos',
4,
'quatro',
3,
'three',
);
const elements = await this.redis.zrange('sortedSet', 0, 2, 'WITHSCORES');
console.log(elements);
// ["one", "1", "dos", "2", "three", "3"] as if the command was `redis> ZRANGE sortedSet 0 2 WITHSCORES`
}
}