当前位置:网站首页>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.
边栏推荐
猜你喜欢

【JZ64 求1+2+3+...+n】

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

TestNg整合Retry代码

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

SST-Calib: A lidar-visual extrinsic parameter calibration method combining semantics and VO for spatiotemporal synchronization calibration (ITSC 2022)

(***Key points***) Flink common memory problems and tuning guide (1)
![【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?](/img/f3/b9256fc04d1c9e15c74d2fc14db0fb.png)
【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?

jmeter接口压力测试-(二)

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

RY-D1/1电压继电器
随机推荐
HJY-F931A/YJ三相电压继电器
Typroa 替代工具marktext
xshell使用技巧(赚分享平台怎么样)
STM32F1读取MLX90632非接触式红外温度传感器
2022全球数字经济大会人工智能专场:AI安全受高度关注
async.js入门
Security tip: FreeType in Qt
Adaptive Control - Simulation Experiment 1 Designing Adaptive Laws Using Lyapunov's Stability Theory
电压跟随器不要随便加
正则表达式快速入门笔记
XYplorer 23多语言,最好的管理软件之一
还在用Swagger?我推荐这款零代码侵入的接口管理神器
数据库事务,JDBC操作和数据类型
Alibaba Cloud OSS Object Storage
decodeURIComponent()、eval()、encodeURIComponent()
Scrapy crawler website image crawling
R语言怎么绘图(一个r语言完整的命令有什么)
oracle export dmp file type as "crash dump file"
Still using Swagger?I recommend this interface management artifact with zero code intrusion
WARN: Establishing SSL connection without server's identity verification is not recommended when connecting to mysql