
commons.box.app.DataStore Maven / Gradle / Ivy
Show all versions of commons-box-app Show documentation
package commons.box.app;
import commons.box.app.misc.LocalDataStore;
import javax.annotation.Nonnull;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* 数据存储 用于通用化缓存实例等场景
*
* TODO 增加 cache2k 支持(与guava相比在 maxSize 和 ttl 控制上更优化)
*/
public interface DataStore {
/**
* 通过 key 获取值
*
* @param key 目标的 key
* @return 目标的 object
*/
O get(K key);
/**
* 通过 key 获取值,支持 object provider
*
* @param key 目标的 key
* @param provider 目标的 object 的 provider
* @return
*/
default O get(K key, Function provider) {
O obj = this.get(key);
if (obj == null && provider != null) {
obj = provider.apply(key);
if (obj != null) this.set(key, obj);
}
return obj;
}
/**
* 通过 key 设置对象
*
* @param key 目标的 key
* @param value 目标的 object
*/
void set(K key, O value);
/**
* 删除一个 key
*
* @param key 目标的 key
*/
void remove(K key);
@Nonnull
public static LocalDataStore local() {
return new LocalDataStore<>();
}
@Nonnull
public static LocalDataStore local(Function provider) {
return new LocalDataStore<>(provider);
}
@Nonnull
public static LocalDataStore local(int size, int timeout, TimeUnit timeUnit) {
return new LocalDataStore<>(size, timeout, timeUnit);
}
@Nonnull
public static LocalDataStore local(int size, int timeout, TimeUnit timeUnit, Function provider) {
return new LocalDataStore<>(size, timeout, timeUnit, provider);
}
}