Feign Interceptor interceptor achieve global request parameter

background

  All interfaces are typically needs to be placed in the third-party API Header or docking Param fixed parameters (the Token, the developer Key, etc.), because it is SpringCloud development tools typically use HTTP Feign. Each method selected copy if appropriate fields, seems to be rather redundant. This time we can use Feign the Interceptor function.

achieve

Talk is cheap,show me the code.

Below a selected particular scene, the need to bring a FeignClient All interfaces a query string: name = Allen

@FeignClient(value = "example", url = "https://api.xxx.com",configuration = MyConfig.class)
public interface ExampleClient {

    @PutMapping(value = "/a")
    AddRes add(@RequestParam("id") String id);

   
    @DeleteMapping(value = "/b")
    DelRes delete(@RequestParam("id") String id);
}

Specify a configuration parameter in the configuration class @FeignClient annotation, the following configuration to achieve the class

public class MyConfig {

    @Bean("myInterceptor")
    public RequestInterceptor getRequestInterceptor() {
        return new MyClientInterceptor();
    }

}

//拦截器实现
class MyClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.query("name","Allen") ;
    }
    
}

Configuration class specified our custom interceptor, the interceptor needs to inherit RequestInterceptor , achieve apply (RequestTemplate requestTemplate) method. In this way we got RestTemplate instance intercepted request, you can drive a throw common parameter friends ~

This call to query, is added a new query param, there are other api such as header, body, etc., can be invoked as needed.

If the process is relatively simple, we can use the Lambda write anonymous inner classes directly in the configuration class, the code looks much more simple.

public class MyConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> template.query("name", "Allen");
    }
    
}

Feign plurality interceptors can, but does not guarantee Spring execution order.

Zero or more {@code RequestInterceptors} may be configured for purposes such as adding headers to
all requests. No guarantees are give with regards to the order that interceptors are applied.

Guess you like

Origin www.cnblogs.com/notayeser/p/12410919.html