China of Responsibility,职责链模式:使多个对象都有机会处理请求,从而避免请求的送发者和接收者之间的耦合关系
接触于开源网关项目soul
git地址:https://github.com/Dromara/soul
通过源码学习总结如下
1.插件化支持,插件采用责任链模式,顺序执行插件
2.热插拔采用zookeeper订阅机制刷新插件集合内部实现为map,通过排序转为list插件集
3.插件的具体实现一只半解,就不说了
其中收获最深的还是对责任链的理解
责任链执行器
private static class DefaultSoulPluginChain implements SoulPluginChain {
private int index;
private final List<SoulPlugin> plugins;
/**
* Instantiates a new Default soul plugin chain.
*
* @param plugins the plugins
*/
DefaultSoulPluginChain(final List<SoulPlugin> plugins) {
this.plugins = plugins;
}
/**
* Delegate to the next {@code WebFilter} in the chain.
*
* @param exchange the current server exchange
* @return {@code Mono<Void>} to indicate when request handling is complete
*/
@Override
public Mono<Void> execute(final ServerWebExchange exchange) {
if (this.index < plugins.size()) {
SoulPlugin plugin = plugins.get(this.index++);
return plugin.execute(exchange, this);
} else {
return Mono.empty();
}
}
}
}
责任链对象执行器
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
其他的业务源码就不贴了,doexcute调用子类具体插件的实现
return doExecute(exchange, chain, selectorZkDTO, rule);
}
具体子类执行器
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorZkDTO selector, final RuleZkDTO rule) {
经过业务处理之后调用责任链执行器的excute继续
chain.execute(exchange);
}
一个轮回之后,到责任链执行器开始下一个责任对象的执行
直到结束
其他开源框架也要责任链的具体实现