dubbox拦截器配置

dubbo是一个被国内很多互联网公司广泛使用的开源分布式服务框架,即使从国际视野来看应该也是一个非常全面的SOA基础框架。作为一个重要的技术研究课题,在当当网我们根据自身的需求,为Dubbo实现了一些新的功能,并将其命名为Dubbox(即Dubbo eXtensions)
dubbox支持REST风格远程调用(HTTP + JSON/XML)
支持基于Kryo和FST的Java高效序列化实现
支持基于嵌入式Tomcat的HTTP remoting体系
升级Spring
升级ZooKeeper客户端
可以参考: https://www.oschina.net/p/dubbox
在开发中,有时候需要限制访问的权限,白名单就是一种方法。对于Java Web应用,Spring的拦截器可以拦截Web接口的调用;而对于dubbo接口,Spring的拦截器就不管用了。

dubbo提供了Filter扩展,可以通过自定义Filter来实现这个功能。


1、拓展Filter

public class TokenInterceptor implements Filter{
    private LoginApi loginApi = new LoginApiImpl();
    private String tokenErrorUrl="http://127.0.0.1:5033/token/tokenError";
 
 
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        HttpServletRequest request = (HttpServletRequest)RpcContext.getContext().getRequest();
        HttpServletResponse response = (HttpServletResponse)RpcContext.getContext().getResponse();
        String token = request.getParameter("token");
        boolean flag = loginApi.validToken(token);
        if (flag) {
            return invoker.invoke(invocation);
        }else {
            AppDomain app=new AppDomain();
            app.setMessage("900"); 
            app.setData(null);
            print(JsonUtil.toJson(app),response);
            return new RpcResult();
        }
    }
    protected void print(String str,HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            response.setContentType("text/html; charset=utf-8" );
            writer = response.getWriter();
            writer.print(str);
        } catch (Exception e) {
             
        } finally {
            CloseUtil.close(writer);
        }
    }
    public LoginApi getLoginApi() {
        return loginApi;
    }
    public void setLoginApi(LoginApi loginApi) {
        this.loginApi = loginApi;
    }
    public String getTokenErrorUrl() {
        return tokenErrorUrl;
    }
    public void setTokenErrorUrl(String tokenErrorUrl) {
        this.tokenErrorUrl = tokenErrorUrl;
    }
}


2、配置文件


在resources目录下添加纯文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter


内容

loginInterceptor=com.XXX.dubbo.web.Interceptor.LoginInterceptor


然后在配置接口是将此拦截器配置上


<dubbo:protocol id="xxxRest" name="rest" port="2000"/>
    <!-- ref:要注入的Service实现 -->
    <dubbo:service interface="com.xxx.api.person.PersonApi" 
                    ref="xxxApi" version="1.0" group="xxx-person"
                    protocol="personRest" filter="loginInterceptor" timeout="60000" />








出自于同事博客

转载:http://xinsir.blog.51cto.com/5038915/1861968






猜你喜欢

转载自blog.csdn.net/hezemin0315/article/details/52957348
今日推荐