본문 바로가기
프로그래밍/TypeORM

[TypeORM] Caching queries

by YuminK 2023. 8. 31.

https://orkhan.gitbook.io/typeorm/docs/caching

 

QueryBuilder메소드(getMany, getOne, getRawMany, getRawOne, getCount)의 메소드 결과를 캐시할 수 있다.

EntityManager나 Repository의 find*, count* 메소드의 결과 또한 캐시할 수 있다.

 

data source의 옵션에서 명시적으로 캐싱을 활성화한다.

{

    type: "mysql",

    host: "localhost",

    username: "test",

    ...

    cache: true

}

 

한번 캐시를 활성화하면 데이터베이스 스키마를 다시 동기화해야 한다. 

CL를 사용하여 migration 또는 synchronize 데이터 소스 옵션을 처리한다.

 

이후에 QueryBuilder에서 쿼리를 위해 캐싱을 활성화한다.

const users = await dataSource

    .createQueryBuilder(User, "user")

    .where("user.isAdmin = :isAdmin", { isAdmin: true })

    .cache(true)

    .getMany()

 

레포지토리 쿼리도 동일하다. 

const users = await dataSource.getRepository(User).find({

    where: { isAdmin: true },

    cache: true,

})

 

이는 모든 어드민 유저를 가져오고 그 결과는 캐시한다. 다음번에 같은 코드가 실행되면 캐시에서 유저 데이터를 얻는다.

기본 캐시는 1초 동안 유효하다. 쿼리 빌더 코드가 호출된 1초 후에는 유효하지 않다.

 

실제로 이는 유저가 3초 동안 150번 유저 페이지를 여는 경우, 오직 3 쿼리만 실행된다는 것을 의미한다.

1초 캐시 기간 동안 추가된 유저는 다른 유저에게 반환되지 않는다.

 

캐시타입을 QueryBuilder를 사용하여 바꿀 수 있다.

const users = await dataSource

    .createQueryBuilder(User, "user")

    .where("user.isAdmin = :isAdmin", { isAdmin: true })

    .cache(60000) // 1 minute

    .getMany()

 

혹은 레포지토리에서...

 

const users = await dataSource.getRepository(User).find({

    where: { isAdmin: true },

    cache: 60000,

})

 

혹은 전역적으로 data source option에서...

 

{

    type: "mysql",

    host: "localhost",

    username: "test",

    ...

    cache: {

        duration: 30000 // 30 seconds

    }

}

 

혹은 QueryBuilder를 통해 cache id를 설정할 수 있다.

 

const users = await dataSource

    .createQueryBuilder(User, "user")

    .where("user.isAdmin = :isAdmin", { isAdmin: true })

    .cache("users_admins", 25000)

    .getMany()

 

Or with Repository:

 

const users = await dataSource.getRepository(User).find({

    where: { isAdmin: true },

    cache: {

        id: "users_admins",

        milliseconds: 25000,

    },

})

 

이는 당신에게 세분화된 캐시 컨트롤을 제공한다.

예를 들어 새로운 유저를 추가할 때, 캐시 results를 클리어할 수 있다.

 

await dataSource.queryResultCache.remove(["users_admins"])

 

기본적으로 TypeORM은 query-result-cache라고 불리는 분리된 테이블을 사용하여 모든 쿼리와 결과를 저장한다. 

테이블 이름은 바꿀 수 있으며, table name 속성에서 처리한다.

{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "database",
        tableName: "configurable-table-query-result-cache"
    }
}

 

캐시를 사용하는 것이 효과적이지 않은 경우, 캐시타입을 "redis"나 "ioredis"로 교체할 수 있다. 

그러면 TypeORM은 모든 캐시 기록을 레디스에 저장할 것이다. 

{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "redis",
        options: {
            host: "localhost",
            port: 6379
        }
    }
}

 

어떤 것을 사용하고 있는지에 따라 node_redis, ioredis_option으로 나뉠 수 있다.

 

... 생략

'프로그래밍 > TypeORM' 카테고리의 다른 글

[TypeORM] Insert using Query Builder  (0) 2023.09.02
[TypeORM] Transactions  (0) 2023.08.31
[TypeORM] Active Record vs Data Mapper  (0) 2023.08.31
[TypeORM] Entity Inheritance  (0) 2023.08.31
[TypeORM] Embedded Entities  (0) 2023.08.31

댓글