[TIL] Redis Caching
06/09/23
![[TIL] Redis Caching](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1688369591316%2F6e0b1bc9-e958-48d3-b5d3-168419fb5501.png&w=3840&q=75)
๐ What I newly learned
Applying caching with Redis
To improve the performance of the API for retrieving hospitals based on location, which involves making repeated calls to the Kakao Mobility API and real-time web scraping of bed occupancy data, I decided to use caching.
Since the topic is related to real-time location-based hospital recommendations, the accuracy of the results should not be compromised. Therefore, I implemented caching in a way that retrieves the cached data only if the hospital is queried for the first time and if the subsequent request is made within 60 seconds (to prevent excessive refreshing). I used the symptom report ID as the key and stored the retrieved hospital data as the value in Redis, with a TTL of 60 seconds.
import { CacheModule } from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-ioredis';
@Module({
imports: [
TypeOrmModule.forFeature([Hospitals]),
CacheModule.register({
name: 'redis-cache',
store: redisStore,
host: 'localhost',
port: 6379,
ttl: 60,
}),
],
// ... Other configurations
})
export class HospitalsModule {}
Implementation of Caching
If the key for the given report ID already exists in the cache, retrieve the cached data from Redis and return it.
If not, perform the business logic as usual, and at the end, add the resulting object to Redis as cached data.
The added data will be valid for 60 seconds. If the user makes a subsequent request to the hospital recommendation API within that time frame, return the cached hospital list to the user.
![[์ฝํ
] ๊ทธ๋ฆฌ๋ ๋ฌธ์ - ๋ฌด์ง์ ๋จน๋ฐฉ ๋ผ์ด๋ธ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1712215455263%2F1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png&w=3840&q=75)
![[์ฝํ
] Bfs ํ ๋งํ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709032619170%2F70056896-c857-444b-9c99-45bfcb466806.png&w=3840&q=75)
![[์ฝํ
] Dfs ๋ฌธ์ ์ ํ - ๊ทธ๋ํ ๋ด์์ ๊ตฌ๋ถํ์ฌ ์นด์ดํธ ํ๊ธฐ](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709019361383%2Fb0585d72-c808-4169-83a9-2724f312e927.png&w=3840&q=75)
![[์ฝํ
] DFS vs BFS](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971211123%2F71f9386c-6a62-43b2-a602-4d084c24d6cf.png&w=3840&q=75)
![[์ฝํ
] ์ฌํ๊ฒฝ๋ก](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971251412%2F27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png&w=3840&q=75)