Dubbo攔截器實現的原理,個人理解就是實現或擴展Dubbo本身的Filter接口(LogFilter implements Filter),而後將這個類在配置文件(META-INF/dubbo/com.alibaba.dubbo.rpc.Filter文本文件)中與一個名稱對應(logFilter),而後在dubbo配置文件中對須要增長攔截器的bean進行配置。java
我在以前本身搭建的消費者當中實現了一個filterspring
1.Consumer端增長LogFilter類,擴展Filterapp
package com.mohrss.service; import com.alibaba.dubbo.rpc.*; public class LogFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { // TODO Auto-generated method stub Result result = null; Long takeTime = 0L; try{ Long startTime = System.currentTimeMillis(); //before filter System.out.println("before filter"); result = invoker.invoke(invocation); if (result.getException() instanceof Exception) { throw new Exception(result.getException()); } takeTime = System.currentTimeMillis() - startTime; System.out.println("TakeTime: " + takeTime); //after filter System.out.println("after filter"); } catch(Exception e){ e.printStackTrace(); result = new RpcResult(e); return result; } return result; } }
2.增長配置文件(META-INF/dubbo/com.alibaba.dubbo.rpc.Filter),給LogFilter類起名。ide
logFilter=com.mohrss.service.LogFilter
3.將logFilter加入須要進行攔截器配置的配置屬性當中。(dubbo-consumer.xml)代理
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd "> <!-- 消費方應用名,用於計算依賴關係,不是匹配條件,不要與提供方同樣 --> <dubbo:application name="consumer" /> <!-- 使用multicast廣播註冊中心暴露發現服務地址 --> <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" /> <!-- 生成遠程服務代理,能夠和本地bean同樣使用testProviderService --> <!-- 對誰攔截,就給誰加filter --> <dubbo:reference id="testProviderService" interface="com.mohrss.service.ProviderService" filter="logFilter" /> </beans>
這時,啓動provider和consumer就能夠看到provider和consumer的控制檯上分別打印出了調用和攔截信息。code
注:原創博客,轉載請註明。xml