I'm using Caffeine as Cache Manager integrated with Spring Cache to avoid multiple unnecesary file downloads. Once I download the file, I have its path, which is returned by the download method.
I would like to delete the file once the cache expires. I tried with removalListener
but it seems it is only triggered when cache is manually cleared.
This is my cache configuration:
@Bean
fun getCacheBuilder() = Caffeine.newBuilder()
.expireAfterWrite(3, TimeUnit.SECONDS)
.removalListener { _: Any?, filePath: Any?, _: RemovalCause ->
Files.delete(Paths.get(filePath.toString()))
}
@Bean
fun getCacheManager(caffeine: Caffeine<Any, Any>): CacheManager {
val caffeineCacheManager = CaffeineCacheManager("myStoredData")
caffeineCacheManager.setCaffeine(caffeine)
return caffeineCacheManager
}
Is there something wrong with this code? Is there any way to automatically trigger the listener when the cache expires?