com.clickhouse.client.cache.CaffeineCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of clickhouse-client Show documentation
Show all versions of clickhouse-client Show documentation
Unified Java client for ClickHouse
package com.clickhouse.client.cache;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import com.clickhouse.client.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);
}
}