当前位置:网站首页>微服务的feign调用header头被丢弃两种解决方案(附源码)
微服务的feign调用header头被丢弃两种解决方案(附源码)
2022-07-27 03:38:00 【时间是一种解药】
问题背景
在使用springcloud的微服务feign调用时,会自动把header自动扔掉,但基本上每个服务都会有一个全局globalId,能够清除调用链路,可以有两种解决方案
注意事项:
- 可以使用文章的代码自己创建工程,也可下载源码进行参考
解决方案一
1 可以在每次远程调用时,使用@RequestHeader注解重新封装请求头
@GetMapping("/mem1")
String mem1(String res, @RequestHeader String globalId);
解决方案二
1 可以使用springcloud提供的feign拦截器RequestInterceptor,拦截请求头重新进行封装
解决方案代码示例
1 feign拦截器配置类
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拦截器功能, 解决header丢失问题 * @Created: IDEA2021 * @author: 蓝染 * @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、使用RequestContextHolder拿到刚进来的请求数据
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
//老请求
HttpServletRequest request = requestAttributes.getRequest();
if (request != null) {
//2、同步请求头的数据(主要是cookie)
//把老请求的cookie值放到新请求上来,进行一个同步
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
}
}
};
return requestInterceptor;
}
}
2 请求测试接口
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() {
//获取当前线程请求头信息(解决Feign异步调用丢失请求头问题)
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//每一个线程都来共享之前的请求数据
RequestContextHolder.setRequestAttributes(requestAttributes);
String a = memFeign.mem1("a", "dsahjkdhsakj54646");
System.out.println(a);
return "success";
}
@GetMapping("/test2")
public String test2() {
//获取当前线程请求头信息(解决Feign异步调用丢失请求头问题)
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//调用微服务之前,每一个线程都来共享之前的请求数据
RequestContextHolder.setRequestAttributes(requestAttributes);
String a = memFeign.mem2("a");
System.out.println(a);
return "success";
}
}
3 feign调用
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 启动类,开启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 依赖导入
<?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 整体目录示例
总结
之前总是获取不到头
作为程序员第 215 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …


Lyric: 哪里都是你
边栏推荐
- centos如何安装mysqldump
- EVT interface definition file of spicy
- js三种遍历数组的方法:map、forEach、filter
- JMeter download and installation
- 你了解微信商户分账吗?
- 卷积神经网络——24位彩色图像的卷积的详细介绍
- Preliminary understanding of NiO
- E-commerce system combined with commodity spike activities, VR panorama continues to bring benefits
- Learning route from junior programmer to architect + complete version of supporting learning resources
- ArrayList与LinkedList区别
猜你喜欢

What is animation effect? What is the transition effect?

2022-07-26:以下go语言代码输出什么?A:5;B:hello;C:编译错误;D:运行错误。 package main import ( “fmt“ ) type integer in

Ribbon-负载均衡原理及部分源码

2022 operation of simulated examination question bank and simulated examination platform for safety production management personnel of hazardous chemical production units

2022年危险化学品经营单位主要负责人复训题库及答案

MySQL: understand the basic knowledge of MySQL and computer

Subject 3: Jinan Zhangqiu line 5

Apachecon Asia preheating live broadcast incubator theme full review

H. 265 web player easyplayer's method of opening video to the public

scala 不可变Map 、 可变Map 、Map转换为其他数据类型
随机推荐
Brightcove任命Dan Freund为首席营收官
php+swoole
Okaleido生态核心权益OKA,尽在聚变Mining模式
Daily question 1: delete continuous nodes with a total value of zero from the linked list
Detailed analysis of trajectory generation tool in psins toolbox
[small sample segmentation] msanet: multi similarity and attention guidance for boosting few shot segmentation
xxx is not in the sudoers file. This incident will be reported
2022危险化学品生产单位安全生产管理人员考试题模拟考试题库模拟考试平台操作
Rust:axum learning notes (1) Hello World
每日一题:从链表中删去总和值为零的连续节点
VR panorama gold rush "careful machine" (Part 1)
DINO 论文精度,并解析其模型结构 & DETR 的变体
BigDecimal踩坑总结&最佳实践
Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化
Ribbon-负载均衡原理及部分源码
标准C语言13
ArrayList与LinkedList区别
法解析的外部符号 “public: virtual __cdecl nvinfer1::YoloLayerPlugin::~YoloLayerPlugin(void)“ “public: virtua
Leetcode:433. minimal genetic change
通信协议综述