framework.service.FlagAdminDefault Maven / Gradle / Ivy
package framework.service;
import lombok.Getter;
import org.springframework.cache.Cache;
/**
* 基于 Cache 的 FlagAdmin 默认实现
*/
public class FlagAdminDefault implements FlagAdmin {
/**
* 默认值
*/
public static final String DEFAULT_VALUE = "1";
/**
* 缓存管理器
*/
@Getter
private final Cache cache;
/**
* 分组名称
*/
@Getter
private final String groupName;
/**
* 默认名称
*/
@Getter
private final String defaultName = "DEFAULT";
/**
* 初始新实例
*
* @param cache 缓存处理器
* @param groupName 缓存名称
*/
public FlagAdminDefault(Cache cache, String groupName) {
this.cache = cache;
this.groupName = groupName;
}
/**
* 缓存键构建
*
* @param name
* @return
*/
protected String buildKey(String name) {
return (this.getGroupName() + name).toUpperCase();
}
@Override
public void setFlag() {
this.setFlag(getDefaultName(), DEFAULT_VALUE);
}
@Override
public void setFlag(String name) {
this.setFlag(name, DEFAULT_VALUE);
}
@Override
public void setFlag(String name, String value) {
String key = this.buildKey(name);
getCache().put(key, value);
}
@Override
public void remove() {
this.remove(getDefaultName());
}
@Override
public void remove(String name) {
String key = this.buildKey(name);
getCache().evict(key);
}
@Override
public boolean hasFlag() {
return this.hasFlag(getDefaultName(), DEFAULT_VALUE);
}
@Override
public boolean hasFlag(String value) {
return this.hasFlag(getDefaultName(), value);
}
@Override
public boolean hasFlag(String name, String value) {
if (value == null) return false;
String key = this.buildKey(name);
Cache.ValueWrapper v = getCache().get(key);
if (v == null) return false;
Object o = v.get();
if (o == null) return false;
return value.equals(o);
}
}