Skip to content

Sohel Ahmed Mesaniya

Redis cache in NestJS

NestJS, Redis, Cache, Example1 min read

Redis is powerful & fast. That is the reason it is used as key-value data storage and cahce system in many web apps. Its example usage in NestJS app by setting and getting cache key-values is demonstrated.

# Installing Dependencies
# Redis Cache
# Links and Miscellaneous

Installing Dependencies

  • npm install --save cache-manager Generic Cache Manager API provider
  • npm install cache-manager-redis-store --save Cache Manager API for Redis storage
  • npm install --save-dev @types/cache-manager Type dependency for TypeScript

Redis Cache

Register CacheModule in AppModule

1import * as redisStore from "cache-manager-redis-store";
2import { CacheModule, Module } from "@nestjs/common";
3import { AppController } from "./app.controller";
4import { AppService } from "./app.service";
5
6@Module({
7 imports: [
8 CacheModule.register({
9 store: redisStore,
10 host: "localhost",
11 port: 6379,
12 }),
13 ],
14 controllers: [AppController],
15 providers: [AppService],
16})
17export class AppModule {}

Controller

app.controller.ts
1import { Controller, Get } from "@nestjs/common";
2import { AppService } from "./app.service";
3
4@Controller()
5export class AppController {
6 constructor(private readonly appService: AppService) {}
7
8 @Get()
9 getHello(): Promise<string> {
10 return this.appService.getHello();
11 }
12}

Service

app.service.ts
1import { Injectable, Inject, CACHE_MANAGER } from "@nestjs/common";
2import { Cache } from "cache-manager";
3
4@Injectable()
5export class AppService {
6 constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
7
8 async getHello(): Promise<string> {
9 // callback way
10 // this.cacheManager.set('foo', 'bar', {ttl: 100000}, (err) => {
11 // this.cacheManager.get('foo', (err, result) => {
12 // console.log(result);
13 // });
14 // });
15
16 await this.cacheManager.set("foo2", "bar2", { ttl: 100000 });
17 const res = await this.cacheManager.get("foo2");
18 console.log(res); // logs "bar2"
19
20 return "Hello World!";
21 }
22}

By sending HTTP GET request at the endpoint of AppController getHello(), bar2 is logged in CLI

Links and Miscellaneous


Previous: Sorting calculated columns in Yii2

Next: Contagion movie end explained better

Newsletter Subscription

Form will be submitted in the new tab

© 2024 by Sohel Ahmed Mesaniya. All rights reserved.
Theme by LekoArts