Mongoose Redis Cache

하려는 것

Mongo DB 앞에 Redis 를 두어, 데이터 캐쉬

최대한 쉽고 간편하게 코딩 할 수 있도록

Library 사용하는걸 추천하지만 어떻게 동작하는지 확인

제약 사항

mongoose에서 Model.hydrate() 지원 여부 확인 필요

이 function을 사용할 수 없으면 redis cache를 할 수 없다. 이유는 redis에서 얻어온 값을 model로 변환해야하기 때문. string -> Model<T>

구현 방법

cache function 추가

mongoose.Query.prototype.cache = function(time = 60 * 10){
  this.cacheable = true;
  // we will talk about cacheTime later;
  this.cacheTime = time;
  return this;
}

Overwrite exec function

mongoose.Query.prototype.exec = async function (){
  // cacheable property 여부에 따라 redis 활용 결정
  const result = await exec.apply(this, arguments);
  // save db data to redis
  return result
}

추가 작업

  • 위의 두 작업은 server init 할떄 읽혀야 한다.
  • Typescript를 사용한다면 cacheable, cacheTime에서 문법 오류가 발생한다. DocumentQuery, Query에 대해 Overwrite 용도로 Interface를 선언한다.
  • redis get 하고 나서 리턴해야할 Model에 따라 hydrate()으로 적절히 변환해주어야 한다.

cache 설정

chainable function 으로써 query 실행이 되기전에 아래의 함수가 읽히기에 호출 순서가 상관이 없다.
findById 역시 chainable function 이므로 query가 exec되지 않는다.

Places.findById(id).cache(60)

추천 Library

확인이 필요한건 사용하는 redis 환경에 따라 지원여부가 결정될 수 있다. 어떤건 redis cluster를 지원하지 않았던거 같다.

Reference

https://dev.to/ahmedmagdy11/building-cache-layer-using-redis-and-mongoose-11kb