当前位置:网站首页>There are two solutions for the feign call header of microservices to be discarded (with source code)
There are two solutions for the feign call header of microservices to be discarded (with source code)
2022-07-27 04:27:00 【Time is an antidote】
Micro service feign call header The head is discarded in two solutions ( Source code attached )
The problem background
In the use of springcloud The micro service feign Invocation time , Will automatically header Throw it away automatically , But basically every service has an overall situation globalId, It can clear the call link , There are two solutions
matters needing attention :
- You can use the code of the article to create your own project , You can also download the source code for reference
Solution 1
1 It can be used in every remote call , Use @RequestHeader Annotations reseal request headers
@GetMapping("/mem1")
String mem1(String res, @RequestHeader String globalId);
Solution 2
1 have access to springcloud Provided feign Interceptor RequestInterceptor, Intercept the request header and reseal
Solution code example
1 feign Interceptor configuration class
package com.lanran.feignheader.config;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/** * @Description: feign Interceptor function , solve header Lost problems * @Created: IDEA2021 * @author: Blue dye * @createTime: 2022-07-02 21:10 **/
@Configuration
public class FeignConfig {
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor() {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
//1、 Use RequestContextHolder Get the request data just came in
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
// Old request
HttpServletRequest request = requestAttributes.getRequest();
if (request != null) {
//2、 Synchronization request header data ( Mainly cookie)
// Put the old request cookie Put the value on the new request , Make a synchronization
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
}
}
};
return requestInterceptor;
}
}
2 Request test interface
package com.lanran.feignheader.controller;
import com.lanran.feignheader.feign.MemFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/** * @Author suolong * @Date 2022/7/22 10:58 * @Version 2.0 */
@RestController
public class FeignController {
@Autowired
MemFeign memFeign;
@GetMapping("/test1")
public String test1() {
// Get the request header information of the current thread ( solve Feign Asynchronous call lost request header problem )
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// Each thread shares the previous request data
RequestContextHolder.setRequestAttributes(requestAttributes);
String a = memFeign.mem1("a", "dsahjkdhsakj54646");
System.out.println(a);
return "success";
}
@GetMapping("/test2")
public String test2() {
// Get the request header information of the current thread ( solve Feign Asynchronous call lost request header problem )
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// Before invoking the microservice , Each thread shares the previous request data
RequestContextHolder.setRequestAttributes(requestAttributes);
String a = memFeign.mem2("a");
System.out.println(a);
return "success";
}
}
3 feign call
package com.lanran.feignheader.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
/** * @Author suolong * @Date 2022/7/22 10:59 * @Version 2.0 */
@FeignClient("mem")
public interface MemFeign {
@GetMapping("/mem1")
String mem1(String res, @RequestHeader String globalId);
@GetMapping("/mem2")
String mem2(String res);
}
4 Start class , Turn on feign
package com.lanran.feignheader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@SpringBootApplication
public class FeignHeaderApplication {
public static void main(String[] args) {
SpringApplication.run(FeignHeaderApplication.class, args);
}
}
5 Dependency import
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lanran</groupId>
<artifactId>feignHeader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>feignHeader</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
6 Example of overall catalog 
summary
Before always can't get to the end
As a programmer 215 An article , Write one line of lyrics at a time and record , Look at how many songs there are in life ,wahahaha …


Lyric: You're everywhere
边栏推荐
- Elastic开源社区:开发者招募
- The difference between ArrayList and LinkedList
- 网工知识角|只需四个步骤,教会你使用SecureCRT连接到eNSP,常用工具操作指南必看
- People don't talk much, engineers don't talk much
- ffmpeg合并视频功能
- Delete the whole line of Excel, and delete the pictures together
- List Simulation Implementation
- [competition reference] pytorch common code snippet and operation collection
- 356 pages, 140000 words, weak current intelligent system of high-end commercial office complex, 2022 Edition
- Rust:axum学习笔记(1) hello world
猜你喜欢

Overview of communication protocols

JMeter learning notes 004-csv file line number control cycle times

Eureka service registry

2022 retraining question bank and answers for main principals of hazardous chemical business units

js三种遍历数组的方法:map、forEach、filter

spark练习案例(升级版)

452 pages, 130000 words, the overall solution of modern smart Township Xueliang project 2022 Edition

Okaleido ecological core equity Oka, all in fusion mining mode

匿名命名管道, 共享内存的进程间通信理解与使用

一张图看懂KingbaseES V9
随机推荐
Using LCD1602 to display ultrasonic ranging
Okaleido tiger will log in to binance NFT in the second round, or continue to create sales achievements
对NIO的初步理解
The difference between ArrayList and LinkedList
【软件工程期末复习】知识点+大题详解(E-R图、数据流图、N-S盒图、状态图、活动图、用例图....)
2022 retraining question bank and answers for main principals of hazardous chemical business units
Redis面试题(2022)
els_ 画矩形、代码规划和备份
Plato farm has a new way of playing, and the arbitrage eplato has secured super high returns
Principle of bean validation --07
电商分账系统重要吗,平台应该如何选择分账服务商呢?
Hash (hash)
Elastic开源社区:开发者招募
数据分析师岗位分析
BSN IPFS(星际文件系统)专网简介、功能、架构及特性、接入说明
xxx is not in the sudoers file. This incident will be reported
php+swoole
JVM调优中的一些常见指令
Framework learning journey: init process startup process
[machine learning network] BP neural network and deep learning-6 deep neural networks (DNN)