Dubbox adds filter function (with code)

In development, sometimes it is necessary to restrict access permissions, and blacklisting is one way. For Java web applications, Spring's interceptor can intercept calls to the web interface; for dubbo interfaces, Spring's interceptor does not work.
Dubbo provides the Filter extension, which can be implemented by customizing the Filter. This article uses an example to demonstrate how to implement the IP blacklist of the dubbo interface.

package com.alibaba.dubbo.demo;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;

public class AuthorityFilter implements Filter {  
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityFilter.class);  
  
    private IpBlackList ipBlackList=new IpBlackList();  
  
    //dubbo is automatically injected through the setter method  
    public void setIpWhiteList(IpBlackList ipWhiteList) {  
        this.ipBlackList = ipWhiteList;  
    }  
  
    @Override  
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {  
        if (!ipBlackList.isEnabled()) {  
            LOGGER.debug("Blacklist disabled");  
            return invoker.invoke(invocation);  
        }  
  
        String clientIp = RpcContext.getContext().getRemoteAddressString();  
        LOGGER.debug("Access ip is {}", clientIp);  
        List<String> allowedIps = ipBlackList.getAllowedIp();  
        if (!allowedIps.contains(clientIp)) {  
            return invoker.invoke(invocation);  
        } else {  
            return new RpcResult();  
        }  
    }  
}


Note: You can only inject other beans through the setter method, and do not mark the annotation!
dubbo will inject these beans by itself, you don't need to mark @Resource to let Spring inject, see extension point loading

2 configuration file
Reference : Call interception extension
Add a plain text file META-INF/dubbo/com.alibaba.dubbo to the resources directory .rpc.Filter, the content is as follows:
[plain] view plain copy
xxxFilter=com.xxx.AuthorityFilter
Modify the provider configuration file of dubbo, and add the configured filter in dubbo:provider, as follows:
[html] view plain copy
<dubbo:provider filter="xxxFilter" /> 

In this way, the IP blacklist function of the dubbo interface can be implemented.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327084440&siteId=291194637