Caching in Kotlin con Caffeine
Caffeine è una delle librerie in Java per il caching.
E' molto usata, anche in ambito web tipo con Spring Boot.
In questo articolo vediamo come usarla in Kotlin.
Se usate Maven:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
Qui sotto un esempio:
import com.github.benmanes.caffeine.cache.Caffeine
import java.util.concurrent.TimeUnit
fun main() {
val cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.initialCapacity(100)
.maximumSize(100)
.build<Int, String>()
cache.put(1, "valore 1");
cache.put(2, "valore 2");
val map: Map<Int, String> = cache.asMap()
map.forEach { (key: Any?, value: Any?) -> println("Chiave: $key, Valore: $value") }
System.out.println(cache.getIfPresent(1))
}
Enjoy!
kotlin maven caffeine cache
Commentami!