[Dubbo开发]Dubbo拦截器(Filter)初探

Dubbo拦截器实现的原理,我的理解就是实现或扩展Dubbo自己的Filter接口(LogFilter implements Filter),然后将这个类在配置文件(META-INF/dubbo/com.alibaba.dubbo.rpc.Filter文本文件)中与一个名称对应(logFilter),然后在dubbo配置文件中对需要增加拦截器的bean进行配置。

我在之前自己搭建的消费者当中实现了一个filter

1.Consumer端增加LogFilter类,扩展Filter

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类起名。

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的控制台上分别打印出了调用和拦截信息。

 注:原创博客,转载请注明。

posted @ 2018-08-06 11:26  圣所SANCTUARY  阅读(5683)  评论(0编辑  收藏  举报