Eureka:擴充套件ClientFilter實現服務註冊自定義過濾

冷冷gg發表於2017-12-03

Jersey clientFilter 過濾

eureka-wiki

image
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
複製程式碼

image

總結:

eureka:
  client:
    fetch-registry: true
複製程式碼
  1. 跟了下原始碼,第一種clientFilter只支援懶載入模式(版本1.6.2)
  2. 自定義filter過濾比clientFilter 更加靈活,因為clientfilter不會限制在eureka-server上的任何東西

相關文章