com.clickhouse.data.cache.CaffeineCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of clickhouse-data Show documentation
Show all versions of clickhouse-data Show documentation
Data processing utilities for ClickHouse
package com.clickhouse.data.cache;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import com.clickhouse.data.ClickHouseCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* Cache based on Caffeine implementation. Please be aware that it's not really
* a LRU cache.
*/
public class CaffeineCache implements ClickHouseCache {
private final Cache cache;
private final Function loadFunc;
/**
* Creates a cache with given capacity, seconds to expire(after access), and
* load function.
*
* @param type of the key
* @param type of the value
* @param capacity capacity of the cache
* @param expireSeconds seconds to expire after access
* @param loadFunc load function
* @return cache
*/
public static ClickHouseCache create(int capacity, long expireSeconds, Function loadFunc) {
return new CaffeineCache<>(capacity, expireSeconds, loadFunc);
}
protected CaffeineCache(int capacity, long expireSeconds, Function loadFunc) {
this.cache = Caffeine.newBuilder().maximumSize(capacity).expireAfterAccess(expireSeconds, TimeUnit.SECONDS)
.build();
this.loadFunc = Objects.requireNonNull(loadFunc, "Non-null load function is required");
}
@Override
public V get(K key) {
return cache.get(key, loadFunc);
}
@Override
public T unwrap(Class clazz) {
return Objects.requireNonNull(clazz, "Non-null class is required").cast(cache);
}
}