本文主要研究一下nacos client的ConfigFilterChainManagerjava
nacos-1.1.3/api/src/main/java/com/alibaba/nacos/api/config/filter/IConfigFilterChain.javagit
public interface IConfigFilterChain {
/**
* Filter aciton
*
* @param request request
* @param response response
* @throws NacosException NacosException
*/
void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException;
}
複製代碼
nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManager.javagithub
public class ConfigFilterChainManager implements IConfigFilterChain {
private List<IConfigFilter> filters = Lists.newArrayList();
public synchronized ConfigFilterChainManager addFilter(IConfigFilter filter) {
// 根據order大小順序插入
int i = 0;
while (i < this.filters.size()) {
IConfigFilter currentValue = this.filters.get(i);
if (currentValue.getFilterName().equals(filter.getFilterName())) {
break;
}
if (filter.getOrder() >= currentValue.getOrder() && i < this.filters.size()) {
i++;
} else {
this.filters.add(i, filter);
break;
}
}
if (i == this.filters.size()) {
this.filters.add(i, filter);
}
return this;
}
@Override
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException {
new VirtualFilterChain(this.filters).doFilter(request, response);
}
//......
}
複製代碼
nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManager.javaapi
public class ConfigFilterChainManager implements IConfigFilterChain {
//......
private static class VirtualFilterChain implements IConfigFilterChain {
private final List<? extends IConfigFilter> additionalFilters;
private int currentPosition = 0;
public VirtualFilterChain(List<? extends IConfigFilter> additionalFilters) {
this.additionalFilters = additionalFilters;
}
@Override
public void doFilter(final IConfigRequest request, final IConfigResponse response) throws NacosException {
if (this.currentPosition != this.additionalFilters.size()) {
this.currentPosition++;
IConfigFilter nextFilter = this.additionalFilters.get(this.currentPosition - 1);
nextFilter.doFilter(request, response, this);
}
}
}
//......
}
複製代碼
nacos-1.1.3/api/src/main/java/com/alibaba/nacos/api/config/filter/IConfigFilter.javabash
public interface IConfigFilter {
/**
* Init
*
* @param filterConfig Filter Config
*/
void init(IFilterConfig filterConfig);
/**
* do filter
*
* @param request request
* @param response response
* @param filterChain filter Chain
* @throws NacosException exception
*/
void doFilter(IConfigRequest request, IConfigResponse response, IConfigFilterChain filterChain)
throws NacosException;
/**
* deploy
*/
void deploy();
/**
* Get order
*
* @return order number
*/
int getOrder();
/**
* Get filterName
*
* @return filter name
*/
String getFilterName();
}
複製代碼
ConfigFilterChainManager實現了IConfigFilterChain接口,其doFilter方法使用filters建立VirtualFilterChain,而後執行其doFilter方法;它提供了addFilter方法,能夠根據filter的order順序添加到filters中ide