Redis 내부 메소드 호출 문제

Chans·2024년 9월 8일
0

Spring

목록 보기
2/2

문제

Controler -> Service의 메소드에 @Cachable를 적용해서 개발을 진행하던 중
Service내에서 @Cacheable메소드를 호출 시 호출이 안되는 문제를 발견했다.

Case 1 캐시 정상

-- ExampleController

private final ExampleService exampleService;

@GetMapping("/test")
public Object test(@PathValiable Long id){
	exampleService.test(id);
}

-- ExampleSerivce

@Cachable(value = "test", key="#id")
public Object test(Long id) {
	return id;
}

Case 2 캐시 안됨

-- ExampleController

private final ExampleService exampleService;

@GetMapping("/test")
public Object test(@PathValiable Long id){
	exampleService.test1(id);
}

-- ExampleSerivce
@Cachable(value = "test", key="#id")
public Object test(Long id) {
	return id;
}

public Object test1(Long id) {
	return test(id);
}

원인

문서에 따르면 Proxy Default Mode는 외부 메서드 (동일하지 않은 Bean)에서 호출하는 경우에만 프록시를 타고 Self(this.xxx())를 호출하는 경우 런타임에 동작하지 않는다. 또한 외부에서 Bean을 호출 하여 Proxy가 인터럽트 했더라도 동일한 Bean에서 this.xxxx()(Self 호출)에서는 Proxy가 동작하지 않게 된다.

해결

해결 방법에는 여러 가지가 있지만, 간단한 해결 방법은 Service 클래스를 나누고 외부 Bean 호출을 통해서 Proxy가 올바르게 동작하게 하는 방법이다.

-- ExampleController

private final ExampleService exampleService;

@GetMapping("/test")
public Object test(@PathValiable Long id){
	exampleService.test1(id);
}

-- ExampleSerivce

private final RedisService redisService;

public Object test1(Long id) {
	return redisService.test(id);
}

-- RedisService
@Cachable(value = "test", key="#id")
public Object test(Long id) {
	return id;
}

0개의 댓글