In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you how to use Feign to set up header dynamically. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
Feign dynamic setting header and principle
Feign is used to make remote calls in the project, and some scenarios require dynamic configuration of header.
The initial approach is to set parameters through @ RequestHeader to achieve dynamic header configuration
For example, @ GetMapping (value = "/ test", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}) String access (@ RequestHeader ("Auth") String auth, @ RequestBody Expression expression)
Although this method can achieve the dynamic configuration of header, it will reduce the interface availability when there are too many parameters, so I want to set header by passing bean.
Let's start with the solution public class HeaderInterceptor implements RequestInterceptor {@ Override public void apply (RequestTemplate requestTemplate) {byte [] bytes = requestTemplate.requestBody (). AsBytes (); Identity identity = JSONObject.parseObject (bytes, Identity.class); requestTemplate.header ("Auth", identity.getSecret ()) }} / * configuration specifies Interceptor**/@FeignClient (name = "test", url = "127.0.0.1 url 8300", configuration = HeaderInterceptor.class) public interface GolangTestHandle2 {@ GetMapping (value = "/ handler", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}) String handle (Identity identity);}
Custom Interceptor implements the RequestInterceptor interface, and the callback method apply provides the RequestTemplate object, which encapsulates all the information of the request. Finally, you specify the interface through configuration, and then you can play whatever you want (for example, get the interface parameters through body and set header dynamically)
It is worth noting that if HeaderInterceptor is injected into the Springboot container, it will take effect globally, that is, if configuration is not specified in time, it will also take effect on the global feign interface. Why? Here's a brief explanation.
First Feign creates a springcontext context for each feign class
Spring gets the feign factory instance by calling getObject
@ Override public Object getObject () throws Exception {return getTarget ();}
Internal call to the FeignClientFatoryBean.getTarget () method
T getTarget () {/ / get feign context FeignContext context = this.applicationContext.getBean (FeignContext.class); / / build feign Builder Feign.Builder builder = feign (context);...}
Build Builder based on feign (FeignContext context)
Protected Feign.Builder feign (FeignContext context) {FeignLoggerFactory loggerFactory = get (context, FeignLoggerFactory.class); Logger logger = loggerFactory.create (this.type) / / @ formatter:off Feign.Builder builder = get (context, Feign.Builder.class) / / required values .logger (logger) / / default springEncoder .encoder (get (context, Encoder.class)) / / default OptionalDecoder .decoder (get (context) Decoder.class)) / / default SpringMvcContrat .contract (get (context, Contract.class)) / / @ formatter:on / / configure the context configureFeign (context, builder) of the feign; return builder;}
Basic configuration items are registered for feign class through FeignClientFactoryBean.configureUsingConfiguration during the build process, which also includes registration of Interceptor
Protected void configureUsingConfiguration (FeignContext context, Feign.Builder builder) {Logger.Level level = getOptional (context, Logger.Level.class); if (level! = null) {builder.logLevel (level);} Retryer retryer = getOptional (context, Retryer.class); if (retryer! = null) {builder.retryer (retryer) } ErrorDecoder errorDecoder = getOptional (context, ErrorDecoder.class); if (errorDecoder! = null) {builder.errorDecoder (errorDecoder);} Request.Options options = getOptional (context, Request.Options.class); if (options! = null) {builder.options (options) } / / get interceptors Map requestInterceptors = context .getInstances (this.contextId, RequestInterceptor.class) from feign context; if (requestInterceptors! = null) {builder.requestInterceptors (requestInterceptors.values ());} if (this.decode404) {builder.decode404 ();}}
ContextId is a specific feign class id, and RequestInterceptor is a specific interface, that is to say, all RequestInterceptor instances are obtained through context.getInstances and registered in builder.
Public Map getInstances (String name, Class type) {AnnotationConfigApplicationContext context = getContext (name); / / use beanNamesForTypeIncludingAncestors if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors (context, type). Length > 0) {return BeanFactoryUtils.beansOfTypeIncludingAncestors (context, type);} return null;}
The beanNamesForTypeIncludingAncestors method is used to get the instance in the factory, which looks not only from feign's factory, but also through the parent-level spring factory (similar to springmvc's factory).
Also because of this method, even if you do not configure configuration in FeignClient, your Interceptor will take effect globally if it is injected into the container through @ Component and other methods, so if you point to let your Interceptor part take effect, do not let it be injected into the Spring container.
Set header information for Feign (in two forms)
When using the microservice SpringCloud family bucket component Fegin, we need to add some sensitive information to our Fegin header (Header) in order to prevent clients from hijacking information while making calls between remote services. Today, my friend asked, to sum up: then there are two common ways to work.
1. Add @ RequestHeader annotation @ PostMapping (value = "/ getPersonDetail") public ServerResponse getPersonDetail (@ RequestBody Map map,@RequestHeader (name = "id") String id) before the method parameter
Dynamic header properties can be passed using @ RequestHeader (name = "id")
two。 Implement the RequestInterceptor interface
Set Header (all Fegin requests)
Import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import feign.RequestInterceptor; import feign.RequestTemplate; @ Configuration public class FeignConfiguration implements RequestInterceptor {@ Override public void apply (RequestTemplate template) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes () HttpServletRequest request = attributes.getRequest () Enumeration headerNames = request.getHeaderNames (); if (headerNames! = null) {while (headerNames.hasMoreElements ()) {String name = headerNames.nextElement () String values = request.getHeader (name); template.header (name, values) }} @ Component@FeignClient (value = "abc", fallback = abcServiceHystric.class, configuration = FeignConfiguration.class) public interface AbcService {} above is all the content of the article "how to use Feign to set up header dynamically". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.