How to intercept feignclients and dynamically change URLs
Working with springcloud, sometimes we should dynamically change the URL of Feignclient, In this article we will show you how to change the URL when executing feignclient.
When Feign is used to make remote calls to Microservices, we can implement the function of intercepting and dynamically changing the URL by implementing the RequestInterceptor interface.
The specific approach is to create a MyRequestInterceptor class and implement the RequestInterceptor interface, implementing the apply () method within it. In this method, we can obtain the request information for calling the remote service and dynamically modify the URL in it.
@Component public class MyRequestInterceptor implements RequestInterceptor { // new URL in ThreadLocal public static ThreadLocal<String> urlHolder = new ThreadLocal<>(); // change url @Override public void apply(RequestTemplate requestTemplate) { String url = urlHolder.get(); if (url != null) { URI currentUri = UriComponentsBuilder.fromUri(requestTemplate.feignTarget().url()).build().toUri(); URI newUri = UriComponentsBuilder.fromUri(currentUri).host(url).build().toUri(); requestTemplate.uri(newUri); urlHolder.remove(); } } }
In the above code, we created a MyRequestInterceptor class and captured each Feign call request by implementing the apply () method of the RequestInterceptor. And in the apply () method, we store and obtain a new URL through ThreadLocal, and then dynamically modify the URL for each Feign's service call by modifying the uri attribute in the RequestTemplate.
When using, simply save the new URL to the MyRequestInterceptor.urlHolder object where it needs to be dynamically changed. For example:
MyRequestInterceptor. urlHolder.set("new URL"); //Calling remote services ResponseEntity<String>response=remoteService. doSomething();
In the above code, we store the new URL in the MyRequestInterceptor.urlHolder object and initiate a Feign call by calling the remote service. At this point, the MyRequestInterceptor class intercepts the request and modifies the URL, then forwards the original Feign call request to the remote service and returns the response result.
From:Is Everything OK
COMMENTS