티스토리 뷰

 

 

 

매번 데이터를 저장하기 위해 데이터베이스를 거치는 것은 번거롭고 오버헤드가 발생하는 작업이다.

 

때문에, DB의 부하도 줄일 겸해서 인메모리에 짧은 시간, 작은 크기의 데이터를 저장해서 사용하는 경우가 많다.

 

대표적인 예가 Redis를 사용해서 캐싱을 하는건데, 스프링 자체에서도 캐시 기능을 제공한다.

 

이전에 비슷한 내용의 글을 작성했는데, 스프링부트에서 굉장히 쉽게 구현이 가능해서 정리해봤다.

 

사용법

별도의 gradle 설정이 필요 없다. 라이브러리도 딱히 받을 필요없음. 

 

1. Config 설정

- Map형식으로 사용하고 싶어서 ConcurrentMapCacheManager 사용함

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("MyCache");
    }
}

2. Service 구현

@Service
@RequiredArgsConstructor
public class CacheService {
    private final CacheManager cacheManager;

	public String saveCache(String value) {
        Cache cache = cacheManager.getCache("MyCache");
        String id = UUID.randomUUID().toString();
        byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
        if (cache != null) {
            cache.put(id, bytes);
        }
        return id;
    }
    
    public String getCache(String id) {
        Cache cache = cacheManager.getCache("MyCache");
        String value = null;
        byte[] bytes = cache.get(id, byte[].class);
        if (bytes != null) {
            value = new String(bytes, StandardCharsets.UTF_8);
        }

        return value;
    }

}

 3. 컨트롤러에서 가져다쓰기

@RestController
@RequiredArgsConstructor
public class PilotController {
	private final CacheService cacheService;
    
    @PostMapping("/cache/test")
    public String testCache(){
        String id = cacheService.saveCache("hello cache");
        System.out.println(cacheService.getCache(id));
        return cacheService.getCache(id);
    }
}

 

4. 결과

 

콘솔
포스트맨

마치며

진짜 실전 압축 방법만 작성해봤다.

 

실전에서는 String 보다는 Object를 더 많이 저장하고 가져다쓰기 때문에, 다음엔 그 내용을 작성해보지 않을까 싶다.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함