Skip to content

Instantly share code, notes, and snippets.

@programmerShinobi
Last active December 21, 2023 04:47
Show Gist options
  • Save programmerShinobi/8f545d5071cfb42b796d48945157d96c to your computer and use it in GitHub Desktop.
Save programmerShinobi/8f545d5071cfb42b796d48945157d96c to your computer and use it in GitHub Desktop.
How to use Time To Live (TTL) Cache in Redis using NestJS Framework
REDIS_HOST=Your_Redis_Host_Is_Actived
REDIS_PORT=Your_Redis_Port_Is_Actived
import {
Controller,
Get
} from '@nestjs/common';
import { AppService } from './app.service';
@Controller({
path: 'your-path',
})
export class AppController {
constructor(private readonly appService: AppService) {
super(AppController.name)
}
@Get()
async yourMethodInController(): string {
return this.appService.yourMethodInService();
}
}
import { Module } from '@nestjs/common';
import { CacheModule, CacheModuleAsyncOptions } from '@nestjs/cache-manager';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { redisStore } from 'cache-manager-redis-store';
import { AppController } from './app.controller';
import { AppService } from './app.service';
const RedisOptions: CacheModuleAsyncOptions = {
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
isGlobal: false,
ttl: 3600,
store: await redisStore({
socket: {
host: config.get<string>('REDIS_HOST') || 'localhost',
port: Number(config.get<string>('REDIS_PORT')) || 6379,
},
}),
}),
};
@Module({
imports: [
CacheModule.registerAsync(RedisOptions)
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}
import {
Inject,
Injectable,
} from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
@Injectable()
export class AppService {
private ttl: number = { ttl: 3600 } as any;
constructor(
@Inject(CACHE_MANAGER)
private readonly cache: Cache,
) {
super(AppService?.name);
}
private async cacheCheck<T>(key: string) {
console.log('From cache check');
const result = await this.cache.get<T>(key);
if (result !== null && result !== undefined) {
console.log(`[${key}] Getting data from cache`);
return result;
}
}
async yourMethodInService<T>(): string {
const _valueInCache = await this.cacheCheck<T[]>(
`cache-key`,
);
if (_valueInCache) {
this.logger.log({ _valueInCache });
return _valueInCache;
}
const value: string = 'This is value of string";
await this.cache.set(
`cache-key`,
value,
this.ttl
);
console.log(value);
return value
}
}
{
...
"dependencies": {
"@nestjs/bull": "^10.0.1",
"@nestjs/cache-manager": "^2.1.1",
"@nestjs/common": "^10.2.10",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.2.10",
"cache-manager": "^5.2.4",
"cache-manager-redis-store": "^3.0.1"
},
"devDependencies": {
"@nestjs/cli": "^10.2.1",
"@nestjs/schematics": "^10.0.3",
"@nestjs/testing": "^10.2.10",
"@types/cache-manager": "^4.0.3",
"@types/express": "^4.17.13",
"@types/jest": "27.4.1",
"@types/node": "^16.0.0"
},
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment