当前位置:网站首页>How to add data to the request header when feign is called remotely
How to add data to the request header when feign is called remotely
2022-07-30 11:11:00 【Self-disciplined watermelon L】
1. Solutions to problems firstBy implementing Feign's RequestInterceptor (interceptor) interface, rewrite the apply method inside, and add custom request header parameters and data input to RequestTemplate.When the request first comes in, it will enter the interceptor, and when the business code makes a remote call, it will also enter the request.
@Componentpublic class FeignClientsExtendInterceptor implements RequestInterceptor {@Overridepublic void apply(RequestTemplate requestTemplate) {// This method is thread safeServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();// When it is not empty, take out the header in the request and set it to the feign request as it isif (null != attributes) {HttpServletRequest request = attributes.getRequest();if (null != request) {// Traversing the settings can also take the entire Header from the request and write it to the RequestTemplateEnumeration headerNames = request.getHeaderNames();if (headerNames != null) {while (headerNames.hasMoreElements()) {String name = headerNames.nextElement();String values = request.getHeader(name);requestTemplate.header(name, values);}}}}// Process the request body parameter information// When feign calls the get interface, it will report a 405 Request method 'POST' not supported error// When you don't need to transmit the information in the request body, you can solve it by commenting the code that processes the request body information// The reason is that when feign sends a request at the bottom layer, it finds that the request body with parameters will be automatically converted into a post request./*Enumeration bodyNames = request.getParameterNames();StringBuilder body = new StringBuilder();if (bodyNames != null) {while (bodyNames.hasMoreElements()) {String name = bodyNames.nextElement();String values = request.getParameter(name);body.append(name).append("=").append(values).append("&");}}if (body.length() != 0) {body.deleteCharAt(body.length() - 1);requestTemplate.body(body.toString());}*/}} 2. Business scenario (to ensure that the caller's information is consistent in subsequent requests)
(1) MQ messages are consumed and remote calls are initiated.
That is, there is no request-related information at this time, but when feign initiates a request, it is necessary to ensure that the information in the request header is the relevant information of the current thread. At this time, the required relevant information can be put into a thread copyIn the middle, by inheriting RequestContextHolder or rewriting a similar class, put the information of the current thread in, and then when feign initiates a remote call, take out the required information and put it into the request header.
(2) Same thread
When the front-end request is made, it will bring a series of verification parameters in the request header, call my service, and need to call other services.In other services, it is necessary to extract or verify the information in the request header.
When feign is called remotely, the bottom layer is to encapsulate the parameters and then make a request. It is a new request, so the header file information in the incoming request from the front end will not be passed, so you can rewrite the RequestInterceptor,Copy the information in the request header intact.
(3) Multi-threaded asynchronous calls to other microservices
The above rewritten code may not be able to obtain the request information of the main thread. The main reason is: RequestContextHolder to obtain the request information. When an asynchronous call is found, after the main thread ends, the child thread cannot obtain the request and will reporterror message.
Solution 1:
By obtaining the request of the main thread, when the front-end call is made, the front-end request will come in. At this time, the sub-thread sharing is enabled, then when the subsequent business is executed, when the asynchronous call is found, after the main thread ends, the sub-thread isInformation about the request can be obtained.
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();// Enable child thread sharing after the above codeRequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//Set child thread sharingSolution 2:
is similar to the processing method of (2) the same thread, put the request and session information of the main thread into ThreadLocal, and transparently transmit it to the child thread to obtain it.
边栏推荐
- 简述controller,service,repository注解的用法(谈谈application.properties的作用)
- The method of parameter passing
- Is it too late to apply for PMP now to take the September exam?Share agile full-true mock questions
- Shell system learning function
- AB测试 总结归纳
- (BUG record) No module named PIL
- 【HMS core】【Analytics Kit】【FAQ】如何解决华为分析付费分析中付款金额显示为0的问题?
- 正则表达式快速入门笔记
- vscode中写markdown格式笔记的配置过程和相关语法
- kubernetes的一些命令
猜你喜欢

Neural Network Study Notes 4 - Autoencoder (including sparse, stacked) (updated)

API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试

Verilog之数码管译码

干货|语义网、Web3.0、Web3、元宇宙这些概念还傻傻分不清楚?(中)

Linux内核设计与实现(十)| 页高速缓存和页回写

易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章
![[AGC] Growth Service 2 - In-App Message Example](/img/fa/9190e45c1532aec908a6c68706629a.png)
[AGC] Growth Service 2 - In-App Message Example

鸿湖万联扬帆富设备开发板正式合入OpenHarmony主干

实现web实时消息推送的7种方案

久经沙场的程序员居然也被某鱼的假程序员骗了,程序员之间的信任应该是最高的,他一个人毁了这种信任感
随机推荐
TensorFlow自定义训练函数
kubernetes的一些命令
拖放事件,dataTransfer,getBoundingClientRect
PanGu-Coder: 函数级的代码生成模型
salesforce使用方法(salesforce authenticator下载)
[100 Solidity Skills] 1. Contract reentrancy attack
【梦想起航】
现在报PMP还来得及参加9月的考试吗?分享敏捷全真模拟题
[Deep Learning] (Problem Record)
- Linear Regression - Small Batch Stochastic Gradient Descent jmeter接口压力测试-(二)
Scrapy crawler website image crawling
4. yolov5-6.0 ERROR: AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' solution
张量篇-初步
MFCC to audio, the effect should not be too funny >V
活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
神经网络学习笔记3——LSTM长短期记忆网络
Swift common extension classes and simple encapsulation
vscode中写markdown格式笔记的配置过程和相关语法
还在用Swagger?我推荐这款零代码侵入的接口管理神器
HJY-F931A/YJ三相电压继电器