본문 바로가기

웹개발/Spring

[Spring]Spring JPA의 1차 캐시는 얼마나 이득을 줄 수 있을까.

Spring JPA는 1차 캐시를 사용한다.

 

1차 캐시는 EntityManager 단위로 생성되기 때문에 EntityManager와 함께 사라진다.

 

사용자의 Request마다 EntityManager가 생성되고, 그 요청을 수행하면 소멸되기 때문에 

 

1차 캐시의 Life cycle은 Transaction과 일치한다.

 

즉 1차 캐시를 사용하면 하나의 Transaction 내에서만 이득을 볼 수 있다. 

 

그 성능이 얼마나 좋은지 간단하게 테스트 해본다.

이런 식의 데이터가 약 500번까지 있다. 

 

이번 실험에서 이 500개의 데이터를 조회함으로써 1차 캐시의 성능을 측정할 것이다 

package hellojpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JpaMain {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");

        EntityManager em = emf.createEntityManager();

        Long beforeTime, afterTime;

        // Initializing time
        em.find(Member.class, 502L);

        try {
            Long id = 0L;
            beforeTime = System.currentTimeMillis();
            for (int i = 1; i <= 500; i++) {
                id++;
                em.find(Member.class, id);
            }
            afterTime = System.currentTimeMillis();

            System.out.println("noCached Time : " + (afterTime - beforeTime));

            beforeTime = System.currentTimeMillis();
            id = 0L;
            for (int i = 1; i <= 500; i++) {
                id++;
                em.find(Member.class, id);
            }
            afterTime = System.currentTimeMillis();

            System.out.println("Cached Time : " + (afterTime - beforeTime));

        } catch (Exception e) {
            System.out.println("ERROR");
        } finally {
            em.close();
            emf.close();
        }
    }
}

 

NoCachedTime 에는 캐시를 사용하지 않은 소요시간이 출력되고

Cached Time에는 캐시를 사용한 상태의 소요시간이 출력된다. 

 

1224 miliSecond vs 18 miliSecond

 

noCached Time을 측정할 때는 find마다 Query가 나가지만 Cached Time을 측정할 때는 1차 캐시에서 데이터를 가져오기 때문에 Query가 나가지 않는다. 

 

효율면에서 어마어마한 차이가 난다.

 

물론 miliSecond 단위이기 때문에 중요하지 않게 여길수도 있지만 상황에 따라 크리티컬할 수도 있을 듯 하다.