10 Eylül 2020 Perşembe

CacheBuilder Sınıfı - Kullanmayın Caffeine Daha İyi

Giriş
Şu satırı dahil ederiz
import google.common.cache.CacheBuilder;
Bu sınıf Cache veya LoadingCache nesnesi yaratmak için kullanılabilir.

build metodu
Cache nesnesi döner.
Örnek
Şöyle yaparız.
Cache<String, Integer> forgetPasswordCache = CacheBuilder.newBuilder()
  .expireAfterAccess(24, TimeUnit.HOURS)
  .build();
build metodu - CacheLoader
LoadingCache nesnesi döner.
Örnek
Şöyle yaparız.
CacheBuilder builder= ...;
cache=builder.build(new CacheLoader(){

  @Override
  public Object load(Object key) throws Exception {
    logger.info("Following data being loaded"+(Integer)key);
    Integer uniqueId=(Integer)key;
    return InputDataPool.getInstance().getAndRemoveDataFromPool(uniqueId);

 }
});
Örnek
Şöyle yaparız.
CacheLoader<String, AtomicInteger> initialValueLoader =
  new CacheLoader<String, AtomicInteger>() {
    @Override
    public AtomicInteger load(String key) {
      // do not care of the key. everybody starts with 0 login attempts.
      return new AtomicInteger(0);
    }
};

LoadingCache<String, AtomicInteger> c = CacheBuilder
  .newBuilder()
  .maximumSize(100000)
  .expireAfterAccess(2, TimeUnit.SECONDS)
  .build(initialValueLoader);
expireAfterAccess metodu
Metodun imzası şöyle.
CacheBuilder<K,V> expireAfterAccess(long duration, TimeUnit unit)
Açıklaması şöyle. Her hangi bir read write işlemi girdinin bayatlama süresini uzatır.
When Does Cleanup Happen?
Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.
Örnek
Şöyle yaparız
CacheBuilder.newBuilder()
  .expireAfterAccess(10, TimeUnit.MINUTES)
  .removalListener(expiredCacheListener())
  .build();
expireAfterWrite metodu
Bu metod yeriner refreshAfterWrite() tercih edilebilir.
Örnek
Şöyle yaparız. Burada nesne siliniyor.
Cache cache = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build();
Örnek
Şöyle yaparız. Burada nesne tekrar yükleniyor. 
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
  .expireAfterWrite(10, TimeUnit.MINUTES)
  .build(
    new CacheLoader<String, Integer>() {
      @Override
      public Integer load(Key key) throws Exception {
        return getKeyFromServer(key);
      }
});
maximumSize metodu
Açıklaması şöyle. Nesne sayısına göre eviction yapar.
Specifies the maximum number of entries the cache may contain.
maximumWeight metodu
Açıklaması şöyle. Cache içindeki her nesne için weigher çağrılır. Nesnelerin ağırlık toplamı maximum değeri geçerse bazı nesneler silinir.
There is no unit for entry weights; rather they are simply relative to each other.
Örnek
Şöyle yaparız.
Cache<String, Cache<String, List<String>>> cache = CacheBuilder.newBuilder()
  .maximumWeight((int) myUpperLimit))
  .weigher((Weigher<String, Cache<String, List<String>>>) (key, val) -> ...)
  .build();
recordStats metodu
Açıklaması şöyle.
Enable the accumulation of CacheStates during the operation of the cache. Without this Cache.stats() will return zero for all statistics.
Eğer bu metod çağrılmamışsa çıktı olarak şunu alırız
CacheStats{hitCount=0, missCount=0, loadSuccessCount=0, loadExceptionCount=0,
  totalLoadTime=0, evictionCount=0}
Örnek
Şöyle yaparız.
LoadingCache<String, Graph> cache = CacheBuilder.newBuilder()
        .refreshAfterWrite(2, TimeUnit.MINUTES)
        .recordStats()           
        .build(new CacheLoader<String, Graph>() {
           ...
});
refreshAfterWrite metodu
Şöyle yaparız.
LoadingCache<String, List<Profile>> loadingCache = CacheBuilder.newBuilder()
  .refreshAfterWrite(5, TimeUnit.MINUTES)
  .expireAfterWrite(5, TimeUnit.MINUTES)
  .build(
    new CacheLoader<String, List<Profile>>() {
      @Override
      public List<Profile> load(String key) throws Exception {
        ...
      }
    }
);
remevalListener metodu
Açıklaması şöyle.
Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.
The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.
Örnek
Şöyle yaparız.
CacheBuilder builder=CacheBuilder.newBuilder()
  .expireAfterWrite(1000, TimeUnit.NANOSECONDS)
  .removalListener(
    new RemovalListener(){
    
      public void onRemoval(RemovalNotification notification) {
        
        logger.info("Following data is being removed:"+notification.getKey());
        if(notification.getCause()==RemovalCause.EXPIRED) {
          logger.fatal("This data expired:");
        } else {
           logger.fatal("This data didn't expired but evacuated intentionally");
        }
    }}
);
Örnek
Şöyle yaparız.
CacheBuilder.newBuilder()
  .expireAfterAccess(5, TimeUnit.SECONDS)
  .maximumSize(MAX_SIZE)
  .removalListener(notification -> LOG.info("Element was : " + notification.getKey()))
  .build(new CacheLoader<String, CacheValue>() {
    @Override
    public CacheValue load(String key) {
      return (CacheValue) value;
    }
});
softValues metodu
Şöyle yaparız.
private static final Cache<String, Buffered> IMAGE_CACHE = CacheBuilder.newBuilder()
    .softValues()
    .build();
weakKeys metodu
Açıklaması şöyle
Note: by default, the returned cache uses equality comparisons (the equals method) to determine equality for keys or values. However, if weakKeys() was specified, the cache uses identity (==) comparisons instead for keys. Likewise, if weakValues() or softValues() was specified, the cache uses identity comparisons for values.

weakValues metodu
Şöyle yaparız
LoadingCache<Object, Test> _foo = CacheBuilder.newBuilder().weakValues()
  .build(new CacheLoader<Object, Test>() {
    @Override public Test load(Object key) throws Exception {
      return new Test(key);
    }});
}
weigher metodu
Şöyle yaparız.
Cache<String, Set<String>> cache = CacheBuilder.newBuilder()
  .maximumWeight(100)
  .weigher((Weigher<String, Set<String>>) (k, v) -> v.size())
  .build();

Hiç yorum yok:

Yorum Gönder