RequestContextHolder多线程获取不到request对象

news/2024/9/13 20:45:21/ 标签: java, 开发语言

RequestContextHolder多线程获取不到request对象,调用feign接口时,在Feign中的RequestInterceptor也获取不到HttpServletRequest问题解决方案。

1.RequestContextHolder多线程获取不到request对象
异常信息,报错如下:

2024-07-09 22:06:32.320 [pool-5-thread-2] ERROR com.mergeplus.handler.ObjectHandler:227 - class: interface org.jeecg.common.system.api.client.SysFeignClient, methodName=mergeRegion, error: {}
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:313)at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:329)at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:324)at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:283)at jdk.proxy2/jdk.proxy2.$Proxy179.getHeaderNames(Unknown Source)at com.mergeplus.handler.ObjectHandler.lambda$doHandler$0(ObjectHandler.java:155)at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run$$$capture(CompletableFuture.java:1768)at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java)at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)at java.base/java.lang.Thread.run(Thread.java:833)

异常错误截图:
在这里插入图片描述
2.解决方案

        // 设置子线程共享(重点)final RequestAttributes attributes = RequestContextHolder.getRequestAttributes();merges.stream().map(e -> CompletableFuture.supplyAsync(() -> {JSONObject returnMap = null;try {if (e.getClientBean() != null) {// 设置当前线程的 RequestAttributes(重点)RequestContextHolder.setRequestAttributes(attributes);Object returnValue = e.getMethod().invoke(e.getClientBean(), jsonObject.get(e.getSourceKey()));if (returnValue == null) {return e;}returnMap = JSON.parseObject(JSON.toJSONString(returnValue));if (returnMap == null || returnMap.isEmpty()) {return e;}result.put(e.getTargetKey(), returnMap.get(jsonObject.get(e.getSourceKey())));} else {if (e.getUrl() == null || e.getUrl().trim().length() == 0) {return e;}//设置Http的HeaderHttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);//设置访问参数HashMap<String, Object> params = new HashMap<>();if (e.getKey() == null || e.getKey().trim().length() == 0) {params.put(e.getSourceKey(), jsonObject.get(e.getSourceKey()));}//设置访问的EntityHttpEntity entity = new HttpEntity<>(params, headers);// todoResponseEntity<Object> exchange = restTemplate.exchange(e.getUrl(), HttpMethod.GET, entity, Object.class);if (exchange == null) {return e;}Object body = exchange.getBody();if (body == null) {return e;}returnMap = JSON.parseObject(JSON.toJSONString(body));if (returnMap == null || returnMap.isEmpty()) {return e;}result.put(e.getTargetKey(), returnMap.get(jsonObject.get(e.getSourceKey())));//                    if (body instanceof Map) {
//                        returnMap = (Map) body;
//                        if (returnMap == null || returnMap.isEmpty()) {
//                            return e;
//                        }
//                        result.put(e.getTargetKey(), returnMap.get(jsonObject.get(e.getSourceKey())));
//                    }}} catch (Exception ex) {log.error("class: {}, methodName={}, error: {}", e.getClientBeanClazz(), e.getMethod().getName(), ex);} finally {RequestContextHolder.resetRequestAttributes(); // 记得在最后重置请求属性(重点)}return e;}, executor)).toList().stream().map(CompletableFuture::join).collect(Collectors.toList());

在这里插入图片描述
在这里插入图片描述
FeignInterceptorConfig代码

package org.jeecg.config;import java.io.IOException;
import java.util.*;import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.config.mqtoken.UserTokenContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.PathMatcherUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.config.sign.interceptor.SignAuthConfiguration;
import org.jeecg.config.sign.util.HttpUtils;
import org.jeecg.config.sign.util.SignUtil;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;/*** @Description: FeignConfig* @author: JeecgBoot*/
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@Slf4j
@Configuration
public class FeignInterceptorConfig {@Beanpublic RequestInterceptor requestInterceptor() {return requestTemplate -> {ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (requestAttributes == null) {return;}//1.获取请求对象HttpServletRequest request = requestAttributes.getRequest();Enumeration<String> headerNames = request.getHeaderNames();if (headerNames == null || !headerNames.hasMoreElements()) {return;}//2.获取请求对象中的所有的头信息(网关传递过来的)while (headerNames.hasMoreElements()) {String name = headerNames.nextElement();//头的名称// 跳过content-length,不然可能会报too many bites written问题if ("content-length".equalsIgnoreCase(name)) {continue;}String value = request.getHeader(name);//头名称对应的值// System.out.println("name:" + name + "::::::::value:" + value);//3.将头信息传递给feign (restTemplate)requestTemplate.header(name,value);//                if (CommonConstant.X_ACCESS_TOKEN.equals(name) && StringUtils.isBlank(value)) {
//                    String token = UserTokenContext.getToken();
//                    requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
//                }}//================================================================================================================//针对特殊接口,进行加签验证 ——根据URL地址过滤请求 【字典表参数签名验证】// todoif (PathMatcherUtil.matches(Arrays.asList(PathMatcherUtil.SIGN_URL_LIST),requestTemplate.path())) {
//            if (PathMatcherUtil.matches(Arrays.asList(SignAuthConfiguration.SIGN_URL_LIST),requestTemplate.path())) {try {log.info("============================ [begin] fegin api url ============================");log.info(requestTemplate.path());log.info(requestTemplate.method());String queryLine = requestTemplate.queryLine();String questionMark="?";if(queryLine!=null && queryLine.startsWith(questionMark)){queryLine = queryLine.substring(1);}log.info(queryLine);if(requestTemplate.body()!=null){log.info(new String(requestTemplate.body()));}SortedMap<String, String> allParams = HttpUtils.getAllParams(requestTemplate.path(),queryLine,requestTemplate.body(),requestTemplate.method());String sign = SignUtil.getParamsSign(allParams);log.info(" Feign request params sign: {}",sign);log.info("============================ [end] fegin api url ============================");requestTemplate.header(CommonConstant.X_SIGN, sign);requestTemplate.header(CommonConstant.X_TIMESTAMP, String.valueOf(System.currentTimeMillis()));} catch (IOException e) {e.printStackTrace();}}//================================================================================================================};}}

3.相关大数据学习demo地址:
https://github.com/carteryh/big-data


http://www.ppmy.cn/news/1475530.html

相关文章

k8s集群新增节点

目前集群状态 如K8S 集群搭建中规划的集群一样 Masternode01node02IP192.168.100.100192.168.100.101192.168.100.102OSCent OS 7.9Cent OS 7.9Cent OS 7.9 目前打算新增节点node03 Masternode01node02node03IP192.168.100.100192.168.100.101192.168.100.102192.168.100.1…

FPGA设计之跨时钟域(CDC)设计篇(1)----亚稳态到底是什么?

1、什么是亚稳态? 在数字电路中,如果数据传输时不满足触发器FF的建立时间要求Tsu和保持时间要求Th,就可能产生亚稳态(Metastability),此时触发器的输出端(Q端)在有效时钟沿之后比较长的一段时间都会处于不确定的状态(在0和1之间振荡),而不是等于数据输入端(D端)的…

升级springboot3.2集成shiro的问题

由于之前的springcloud相关版本太久&#xff0c;很多新功能无法使用&#xff0c;所以打算抽时间把代码的版本做一下升级。使用最新版的springboot3.2&#xff0c;发现shiro过滤器无效。经检查发现原因&#xff1a; springboot3.x使用的是JDK17&#xff0c;从jdk8以后javax.serv…

【数据结构】单链表 双向链表

目录 链表链表的分类单链表单链表接口的实现内部类头插法尾插法任意位置插入查找是否包含关键字key是否在单链表当中删除第一次出现关键字为key的节点删除所有值为key的节点得到单链表的长度清空链表单链表的优缺点 双向链表双向链表接口的实现内部类头插法尾插法任意位置插入查…

微信小程序 - 本地存储 增加有效期

小程序的本地存储API提供了wx.setStorageSync和wx.setStorage来存储数据&#xff0c;注意的是&#xff0c;小程序的本地存储并没有明确的有效期设置&#xff0c;存储的数据在不超过限制的情况下&#xff0c;会一直保留。 一、小程序本地存储API 小程序的本地存储API提供了设置…

32路串口服务器 应用领域

32路串口服务器在多个领域有着广泛的应用&#xff0c;以下是详细的应用实例&#xff1a; 一、工业自动化 在工业自动化领域&#xff0c;32路串口服务器发挥着举足轻重的作用。传统的工业设备往往采用串口通信方式&#xff0c;而串口服务器能够将这些设备接入网络&#xff0c;…

800 元打造家庭版 SOC 安全运营中心

今天,我们开始一系列新的文章,将从独特而全面的角度探索网络安全世界,结合安全双方:红队和蓝队。 这种方法通常称为“紫队”,集成了进攻和防御技术,以提供对威胁和安全解决方案的全面了解。 在本系列的第一篇文章中,我们将指导您完成以 100 欧元约800元左右的预算创建…

金南瓜科技的SECS/GEM解决方案

1. 高稳定性和可靠性&#xff1a;金南瓜SECS/GEM解决方案已在多家知名半导体工厂中稳定运行&#xff0c;实现了7*24小时无重启无故障超过3年时间 。 2. 符合国际标准&#xff1a;金南瓜的解决方案符合SEMI E4、E5、E30、E37通信协议&#xff0c;确保与国际标准的兼容性&#x…

《RWKV》论文笔记

原文出处 [2305.13048] RWKV: Reinventing RNNs for the Transformer Era (arxiv.org) 原文笔记 What RWKV(RawKuv):Reinventing RNNs for the Transformer Era 本文贡献如下&#xff1a; 提出了 RWKV 网络架构&#xff0c;结合了RNNS 和Transformer 的优点&#xff0c;同…

星环科技推出语料开发工具TCS,重塑语料管理与应用新纪元

5月30-31日&#xff0c;2024向星力未来数据技术峰会期间&#xff0c;星环科技推出一款创新的语料开发工具——星环语料开发工具TCS&#xff08;Transwarp Corpus Studio&#xff09;&#xff0c;旨在通过全面的语料生命周期管理&#xff0c;极大提升语料开发效率&#xff0c;助…

prompt第三讲-PromptTemplate

文章目录 前提回顾PromptTemplateprompt 模板定义以f-string渲染格式以mustache渲染格式以jinja2渲染格式直接实例化PromptTemplatePromptTemplate核心变量 prompt value生成invokeformat_prompt(不建议使用)format(不建议使用) batchstreamainvoke PromptTemplate核心方法part…

Redis实战—秒杀优化(Redis消息队列)

目录 回顾 基于阻塞队列实现程序异步优化 优化代码 总结 Redis消息队列 初始消息队列 基于List结构模拟消息队列 基于PubSub的消息队列 基于Stream的消息队列 基于Stream的消息队列-消费者组 总结 代码实现 回顾 我们回顾一下前文下单的流程&#xff0c;当用户发起…

python:使用openpyxl模块处理excel

前言 最近在实践excel的处理&#xff0c;在此途中&#xff0c;我彻底抛弃了xlwt xlrd的组合&#xff0c;投入了openpyxl这一模块的怀抱。 并成功实现了excel单元格数据的快速访问、修改、样式保持&#xff0c;以及添加填充色等功能。 至于为什么写这个博客&#xff0c;主要是因…

Interpretability 与 Explainability机器学习

在机器学习的范畴中&#xff0c;“Interpretability”&#xff08;可解释性&#xff09;和“Explainability”&#xff08;可解释性&#xff09;尽管在含义上有重叠部分&#xff0c;但仍存在一些微妙的差异和重点的不同。 “Interpretability”主要强调模型自身的结构和运作方式…

科普文:微服务技术栈梳理

概叙 如上两图所示&#xff0c;微服务架构下&#xff0c;需要的组件很多&#xff0c;上面中也并未列全。下面将梳理一下国内微服务架构下&#xff0c;用到的技术栈&#xff0c;仅供参考。 科普文&#xff1a;12种常见的软件架构-CSDN博客 没有最好的架构&#xff0c;只有最适…

【Android面试八股文】组件化在项目中有什么意义?

一、没有组件化会出现什么问题? 早期的单一分层模式 问题一:无论分包怎么做,随着项目增大,项目失去层次感,后面接手的人扑街问题二:包名约束太弱,稍有不注意,就会不同业务包直接互相调用,代码高耦合问题三:多人开发在版本管理中,容易出现代码覆盖冲突等问题二、组件…

[linux] git push时需要输入user 和keyword

git clone的要是ssh链接&#xff01;&#xff01;&#xff01;&#xff01; 1、用户名和邮箱 git config --global user.name "name" git config --global user.email "email" 2、生成ssh key (ED25519) ssh-keygen -t ed25519 -C "<自定义内容&g…

数据结构:顺序表+链表

数据结构&#xff1a;顺序表链表 一。顺序表&#xff1a; 首先在了解顺序表和链表之前&#xff0c;先了解一下线性表&#xff0c;**线性表&#xff08;linear list&#xff09;**是n个具有相同特征元素的有限序列 &#xff0c;在逻辑上是线性结构&#xff0c;也就是一条连续的…

[k8s源码]2.CURD deployment

加载kubernetes配置 使用 clientcmd方法&#xff0c;是通过"k8s.io/client-go/tools/clientcmd"包加载的。这个函数返回的是config和error两个值。可以看到返回的config是一个指针变量。 func clientcmd.BuildConfigFromFlags(masterUrl string, kubeconfigPath str…

08 从项目概念到技术概念

我们从技术转型到管理的路上&#xff0c;如果没有贵人引路&#xff0c;基本上都是要先从项目管理这关过。这其实是一件好事&#xff1b;项目管理里面很多琐碎的知识点&#xff0c;非常有用。我今天想举个例子是项目管理过程中经常提到的 “输入-输出”。 ## 1. 好奇的 DDD DD…