[Dubbo & Zookeeper] 6. Add a whitelist for the dubbo interface -- Use of dubbo Filter,
In development, you sometimes need to restrict access permissions. whitelist is a method. For Java Web applications, Spring interceptor can intercept Web interface calls, while for dubbo interfaces, Spring interceptor does not work.
Dubbo provides Filter extensions, which can be implemented through custom filters. This article uses an example to demonstrate how to implement an IP whitelist for the dubbo interface.
1. Extended Filter
Implement the com. alibaba. dubbo. rpc. Filter interface:
Public class AuthorityFilter implements Filter {private static final Logger LOGGER = LoggerFactory. getLogger (AuthorityFilter. class); private IpWhiteList ipWhiteList; // dubbo automatically injects public void setIpWhiteList (IpWhiteList ipWhiteList) {this. ipWhiteList = ipWhiteList;} @ Override public Result invoke (Invoker <?> Invoker, Invocation invocation) throws RpcException {if (! IpWhiteList. isEnabled () {LOGGER. debug ("disabled by whitelist"); return invoker. invoke (invocation);} String clientIp = RpcContext. getContext (). getRemoteHost (); LOGGER. debug ("access ip: {}", clientIp); List <String> allowedIps = ipWhiteList. getAllowedIps (); if (allowedIps. contains (clientIp) {return invoker. invoke (invocation) ;}else {return new RpcResult ();}}}
Note: Only other beans can be injected using the setter method, and annotations are not required!
Dubbo injects these beans by itself, and does not need to mark @ Resource for Spring injection.
2. Configuration File
Add the plain text file META-INF/dubbo/com. alibaba. dubbo. rpc. Filter in the resources directory. The content is as follows: xxxFilter = com. xxx. AuthorityFilter
Modify the dubbo provider configuration file and add the configured filter to dubbo: provider. The content is as follows: <dubbo: provider filter = "xxxFilter"/>
In this way, you can implement the IP whitelist function of the dubbo interface.
Source: http://blog.csdn.net/mj158518/article/details/47379799