Eureka:扩展ClientFilter实现服务注册自定义过滤

Java框架

浏览数:65

2020-6-1

AD:资源代下载服务

Jersey clientFilter 过滤

eureka-wiki

POM依赖:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19.1</version>
</dependency>

实现抽象类ClientFilter的handle方法

public class IpCilentFilter extends ClientFilter {
    @Override
    public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
        //响应对象的处理
        ClientResponse response = this.getNext().handle(clientRequest);
        return response;
    }
}

注入clientFilter

 @Bean
public DiscoveryClientOptionalArgs discoveryClientOptionalArgs() {
    DiscoveryClientOptionalArgs discoveryClientOptionalArgs = new DiscoveryClientOptionalArgs();
    discoveryClientOptionalArgs.setAdditionalFilters(Collections.singletonList(new IpCilentFilter()));
    return discoveryClientOptionalArgs;
}

自定义filter过滤

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean registration = new FilterRegistrationBean(new ServerRequestAuthFilter());
    registration.addUrlPatterns("/*");
    return registration;
}

public class ServerRequestAuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws IOException, ServletException {
        //业务实现,根据请求的IP或者参数判断是否可以执行注册或者访问
        filterChain.doFilter(request, response);
    }
}

拦截具体客户端注册、续约、下线请求,请参考 /eureka/apps

com.netflix.eureka.resources.ApplicationResource

总结:

eureka:
  client:
    fetch-registry: true
  1. 跟了下源码,第一种clientFilter只支持懒加载模式(版本1.6.2)
  2. 自定义filter过滤比clientFilter 更加灵活,因为clientfilter不会限制在eureka-server上的任何东西
  3. 源码可以参考:https://gitee.com/log4j/pig

作者:冷冷gg