1.新增类ValidationFilter继承阿里巴巴的Filter
package com.filter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.alibaba.dubbo.rpc.*;
/** * Description: * author: LinQin * date: 2018/06/08 */
public class ValidationFilter implements Filter {
@Override
public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException {
Properties prop = new Properties();
InputStream in = ValidationFilter.class.getResourceAsStream("/ipwhitelist.properties");
String clientIp = RpcContext.getContext().getRemoteHost();//客户端ip
try {
prop.load(in);
String ipwhitelist = prop.getProperty("ipwhitelist");//ip白名单
if (ipwhitelist.contains(clientIp)) {
return invoker.invoke(invocation);
} else {
return new RpcResult(new Exception("ip地址:"
+ clientIp + "没有访问权限"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (RpcException e) {
throw e;
} catch (Throwable t) {
throw new RpcException(t.getMessage(), t);
}
return invoker.invoke(invocation);
}
}
2.安装阿里巴巴的约定新建配置文件,指定上面的类
注意:路径和配置文件名称必须一致
com.alibaba.dubbo.rpc.Filter
validation=com.filter.ValidationFilter
3.配置ip白名单
resource 目录
ipwhitelist.properties
ipwhitelist=192.168.1.19,192.168.1.158
4.配置服务端dubbo配置
<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="common-service" />
<dubbo:registry protocol="zookeeper" address="193.112.76.194:2181" />
<dubbo:protocol name="dubbo" port="20880" />
<dubbo:provider filter="validation" delay="-1" timeout="6000" retries="0"/>
<dubbo:service interface="com.service.UserService" ref="userService" />
<bean id="userService" class="com.service.UserServiceImpl">bean>
beans>
filter="validation"
表示开启拦截。
启动流程:
启动会先读取dubbo的配置filter的值,对应METE-INF里面的配置的值,找到class进行过滤。
测试:
启动服务,由其他ip的消费者调用,报错
这个错误刚好是我们Fileter类抛出的信息。
不过一般会使用自定义异常进行出来,然后抛出自定义异常。spring框架统一对这类的权限进行特有的页面提示。或者是json返回。