自构建多级缓存
一、背景说明
准备使用责任链模式,构建多级缓存链,依次逐级向下取值,直到取到值为止。将取到的值再逐级赋值给未取到值的缓存级。
二、定义多级List
链路接口类Chain
public interface Chain {
String get(String key );
}
缓存公用接口
public interface CacheClient {
String get(Chain chain, String key);
}
缓存实现类
public class OneCacheClient implements CacheClient{
private String get(String key){
//......
}
private String set(String key,String value){
//......
}
public String get(Chain chain, String key){
String value = this.get(key);
if(StringUtils.isBlank(key)){
value = chain.get(key);
}
if(StringUtils.isBlank(key)){
this.set(key,value);
}
}
}
public class TwoCacheClient implements CacheClient{
private String get(String key){
//......
}
private String set(String key,String value){
//......
}
public String get(Chain chain, String key){
String value = this.get(key);
if(StringUtils.isBlank(key)){
value = chain.get(key);
}
if(StringUtils.isBlank(key)){
this.set(key,value);
}
}
}
public class ThreeCacheClient implements CacheClient{
private String get(String key){
//......
}
private String set(String key,String value){
//......
}
public String get(Chain chain, String key){
String value = this.get(key);
if(StringUtils.isBlank(key)){
value = chain.get(key);
}
if(StringUtils.isBlank(key)){
this.set(key,value);
}
}
}
三、定义内部类
public class MultiCacheProxy {
public static String get(List<CacheClient> list, String key ){
return new DefaultChain(list).get(key);
}
private static class DefaultChain implements Chain {
private List<CacheClient> list = null;
private int i = -1;
public DefaultChain(List<CacheClient> list){
this.list = list;
}
@Override
public String get(String key) {
String value = null;
i++;
if(i >= list.size()){
return value;
}
CacheClient cache = list.get(i);
if(null != cache){
value = cache.get(this,key);
}
return value;
}
}
}
四、测试类测试
public static void main(String[] args) {
List<CacheClient> list = new ArrayList<>();
list.add(new OneCacheClient());
list.add(new TwoCacheClient());
list.add(new ThreeCacheClient());
String cacheKey = "Timer_bin_key"
String value = YaoMultiCacheProxy.get(list,cacheKey);
}