즐겁게/anything

ExpiringMap(net.jodah) 지정한 시간 동안만 저장되고 자동 삭제

파이브빈즈 2022. 11. 2. 00:07

지정한 시간동안 지정한 최대 개수만큼만 저장했다가 자동으로 삭제되는 맵, 캐시와 유사

: A high performance, low-overhead, zero dependency, thread-safe ConcurrentMap implementation that expires entries.

 

참조: https://github.com/jhalterman/expiringmap

 

GitHub - jhalterman/expiringmap: A high performance thread-safe map that expires entries

A high performance thread-safe map that expires entries - GitHub - jhalterman/expiringmap: A high performance thread-safe map that expires entries

github.com

 

- maven repository

<dependency>
    <groupId>net.jodah</groupId>
    <artifactId>expiringmap</artifactId>
    <version>0.5.10</version>
</dependency>

- 사용법

// ExpiringMap 생성
// 최대 10000개까지, 맵에 삽입된 후 10분동안 보관 후 자동 삭제
Map<String, String> map = ExpiringMap.builder()
		  .expirationPolicy(ExpirationPolicy.CREATED)	// 맵에 삽입된 후
		  .maxSize(10000)	// 최대 10000개까지
		  .expiration(10, TimeUnit.MINUTES)	//  10분동안 보관
		  .expirationListener((key, value) -> System.out.println("--- key expired: " + key) )  // 맵에서 삭제될때 로그기록
		  .build();

map.put("key-1", "value-1");
map.put("key-2", "value-2");
map.put("key-3", "value-3");
map.put("key-4", "value-4");
map.put("key-5", "value-5");

맵의 삭제정책 ExpirationPolicy는 ExpirationPolicy.CREATED와 ExpirationPolicy.ACCESSED 중에 선택 가능하며, 

ACCESSED 는 get() 메소드가 호출된 시점 기준

 

설정한 시간이 지나면 map에서 삭제되는 지 테스트해보면 됨