1 Druid中责任链应用
在Druid的监控功能通过FilteChain模式实现。主要包括Fiter、FilterChain、Method三个元素。
1 Filter
1 2 3 |
public interface Filter { void process(FilterChain chain, Method method); } |
定义一个前置过滤器和后置过滤器:
(1)前置过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class BeforeFilter implements Filter { public void process(FilterChain chain, Method method) { // 1.do something before beforeProcess(); // 2. chain.process(); } private void beforeProcess() { System.out.println("do something before"); } } |
(2)后置过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class AfterFilter implements Filter { public void process(FilterChain chain, Method method) { // 1. 执行chain chain.process(); // 2.do something after afterProcess(); } private void afterProcess() { System.out.println("do something after"); } } |
2 FilterChain
定义接口
1 2 3 4 |
public interface FilterChain { void process(); Filter nextFilter(); } |
具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class FilterChainImpl implements FilterChain { private List<Filter> filterList = Lists.newArrayList(); private Method method; private int index = 0; FilterChainImpl(Method method) { this.method = method; filterList.add(new AfterFilter()); filterList.add(new BeforeFilter()); } public void process() { if (index < filterList.size()) { nextFilter().process(this, method); } else { method.process_direct(); } } public Filter nextFilter() { return filterList.get(index++); } } |
3、定义Method
1 2 3 4 5 6 7 8 9 10 11 |
public class Method { public void process() { System.out.println("filter before process_direct"); new FilterChainImpl(this).process(); } public void process_direct() { System.out.println("process direct"); } } |
4、测试
1 2 3 4 5 6 7 |
public class Test { public static void main(String[] args){ Method method = new Method(); FilterChainImpl filterChain = new FilterChainImpl(method); filterChain.process(); } } |
执行结果为:
1 2 3 |
do something before process direct do something after |