非web请求调用feign接口导致的request信息校验失败问题

首先要明确一点的是 feign接口的远程调用其实就是http请求,也就是web请求,那么就需要设置request域对象的相关信息

如果是通过客户端(pc端、移动端)进行的接口请求,会将当前请求的request域对象信息例如token等都会与当前请求的主线程绑定,就可以直接调用。

但是如果是非客户端发起的请求,比如定时任务、队列消费、异步线程(客户端发起了请求,主线程中带有request域对象信息,但是如果在主线程的业务中开启了子线程,那么request域对象信息是不会由主线程传递给子线程的,因为每个线程都有它各自的threadLocal对象)等发起的请求,这些请求由于不是客户端发起,是非web请求,因此本身就不存在request域对象信息,因此在这些方式发起的请求去调用feign接口的时候是不存在request域对象信息的,所以就会出现异常。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.oauth2ClientContext': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is 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.

解决办法:

feign为我们提供了feign的拦截器RequestInterceptor,这个拦截器可以拦截所有的feign接口调用,
这样我们就可以为非web请求的feign调用设置一个自定义的request
 

package com.zhgw.dev.videoAccess.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
    //获取上下文
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getCredentials() != null){
            String token = authentication.getCredentials().toString();
            requestTemplate.header("Authorization","Bearer"+token);
            log.info("获取了请求头信息:"+token);
        }
        //添加其他请求头信息
        requestTemplate.header("Tenantid","******************");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值