모르지 않다는 것은 아는것과 다르다.

Spring

Spring Cache Abstraction

채마스 2022. 3. 19. 21:01

Spring Cache Abstraction 란?

  • 애플리케이션에 "투명하게(transparently)" 캐시를 넣어주는 기능이다.
  • 메소드, 클래스에 적용 가능하다.
  • 캐시 인프라는 스프링 부트 자동 설정으로 세팅되고, 프로퍼티로 관리 가능하다.
  • 캐시가 있건 없건, 시스템의 기대 동작은 동일해야 한다. -> 목표는 성능이다.

 

설정

  • 아래와 같이 디펜던시를 추가해 준다.
implementation 'org.springframwork.boot:spring-boot-starter-cache'
  • 아래와 같이 @EnableCaching 을 붙여준다.
@EnableCaching
@SpringBootApplication
public class ServiceDeskApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceDeskApplication.class, args);
    }

}

 

코드 예시

@Getter
@Setter
@AllArgsConstructor(staticName = "of")
@NoArgsConstructor
public class Person implements Serializable {

    private String name;
    private int age;

}
  • 위와 같이 Serializable 인터페이스를 상속받는다. -> 캐시에 저장될때 직렬화하기 위함이다.
@Repository
@RequiredArgsConstructor
public class PersonRepository {

    private final Map<String, Person> storage;

    @Cacheable("person")
    public Person getPerson(String name) {
        System.out.println("repo 에 접근합니다.");
        return storage.get(name);
    }

    public Person enroll(String name, int age) {
        return storage.put(name, Person.of(name, age));
    }
}
  • 위와 같이 캐시를 적용시키고 싶은 메소드에 @Cacheable 애노테이션을 붙여줌으로써 캐시를 적용시킬 수 있다.
  • "person" 와 매개변수의 조합으로 키가 만들어 진다.

 

 

Config 설정

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(name -> name + ":")
                .entryTtl(Duration.ofSeconds(10))
                .serializeKeysWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

    }

}
  • 위와 같이 캐시에 저장될때 prefix 를 설정해 줄 수 있다.
  • 또한 ttl 을 설정해서 만료시간을 설정할 수 있다.
  • 캐시에 저장될때 json 타입으로 보기 좋게 저장하기위한 설정도 해줄 수 있다.
    • 여기서 serialization 을 설정했으므로 Person 객체에 Serializable 를 상속받지 않아야 한다.




 

REFERENCES

  • 김은호님의 Spring Boot

'Spring' 카테고리의 다른 글

Handler Methods  (0) 2022.04.09
함수 기반 API 설계  (0) 2022.03.19
@ControllerAdvice  (0) 2022.03.19
설정파일(Properties) 관리  (0) 2022.03.19
Null Safety  (0) 2022.03.14