在开发dubbo接口时,有时可能会限制接口的访问,ip白名单即是一种。在dubbo中,通过扩展Filter接口,可以实现IP白名单的功能。

先定义一个配置IP白名单的bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Created by j.tommy on 2017/11/4.
*/
public class IPWhiteList {
private boolean isEnabled; // 是否启用白名单
private List<String> allowIps; // 允许的白名单列表
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public List<String> getAllowIps() {
return allowIps;
}
public void setAllowIps(List<String> allowIps) {
this.allowIps = allowIps;
}
}

然后我们实现dubbo的Filter接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Created by j.tommy on 2017/11/4.
*/
public class IPWhiteListFilter implements Filter{
private IPWhiteList ipWhiteList;
public void setIpWhiteList(IPWhiteList ipWhiteList) {
this.ipWhiteList = ipWhiteList;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (!ipWhiteList.isEnabled()) {
System.out.println("dubbo IP白名单被禁用!");
return invoker.invoke(invocation);
}
String clientIp = RpcContext.getContext().getRemoteHost();
if (ipWhiteList.getAllowIps().contains(clientIp)) {
return invoker.invoke(invocation);
}
System.out.println("dubbo客户端IP[" + clientIp + "]不在白名单,禁止调用!");
return new RpcResult();
}
}

在/resources目录下,新建META-INF/dubbo目录,并新建一个名为com.alibaba.dubbo.rpc.Filter的文本文件

内容如下:

1
ipWhiteListFilter=com.tommy.service.provider.filter.IPWhiteListFilter

dubbo的配置文件中增加filter的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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="demo-provider"/>
<dubbo:registry address="multicast://224.5.6.7:1234"/>
<dubbo:protocol name="dubbo" port="20880" />
<dubbo:provider filter="ipWhiteListFilter"/>
<dubbo:service interface="com.tommy.service.DemoService" ref="demoService"/>
<bean id="demoService" class="com.tommy.service.provider.DemoServiceImpl"/>
<bean id="ipWhiteList" class="com.tommy.service.provider.bean.IPWhiteList">
<property name="enabled" value="true"/>
<property name="allowIps">
<list>
<value>127.0.0.1</value>
<value>192.168.71.170</value>
</list>
</property>
</bean>
</beans>

参考:http://blog.csdn.net/mj158518/article/details/47379799