8 Haziran 2023 Perşembe

Caffeine Cache Arayüzü

Giriş
Şu satırı dahil ederiz
import com.github.benmanes.caffeine.cache.Cache;
put metodu
Örnek
Şöyle yaparız
Cache<String, String> cache = Caffeine.newBuilder().build();
cache.put("key", "value");
cache.getIfPresent("key");
stats metodu
Örnek
Şöyle yaparız
Cache<String, String> cache = Caffeine.newBuilder()
        .recordStats() // Enabled statistics collection
        .build();

// Add to the cache
cache.put("1", "value_1");
cache.put("2", "value_2");

// Simulate hit and miss from cache
cache.getIfPresent("1");
cache.getIfPresent("3");

System.out.println(cache.stats());
Çıktı şöyle
"CacheStats"{
   hitCount=1,
   missCount=1,
   loadSuccessCount=0,
   loadFailureCount=0,
   totalLoadTime=0,
   evictionCount=0,
   evictionWeight=0
}



Caffeine Kullanımı

Maven
Şu satırı dahil ederiz
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>3.1.6</version>
</dependency>
Caffeine.newBuilder() çağrısı yaparak bir Cache  veya LoadingCache nesnesi yaratırız

Caffeine'in hızlı olmasının sebebi şöyle.
The main difference is because Caffeine uses ring buffers to record & replay events, whereas Guava uses ConcurrentLinkedQueue. The intent was always to migrate Guava over and it made sense to start simpler, but unfortunately there was never interest in accepting those changes. The ring buffer approach avoids allocation, is bounded (lossy), and cheaper to operate against.
Thread
Açıklaması şöyle.
Caffeine, like Guava, does not create threads so it cannot schedule work outside of user activity.
Caffeine AsyncCache Arayüzü CompletableFuture nesnesi döner. Bu arayüz ise gerçek nesne döner.

Scheduler
Açıklaması şöyle.
Guava performs expiration on calling threads, so nothing occurs until the next access. You could use Caffeine with a configured scheduler which will perform the work on a background thread.