SpringBoot异步任务获取HttpServletRequest

前言

在使用框架日常开发中需要在controller中进行一些异步操作减少请求时间,但是发现在使用@Anysc注解后会出现Request对象无法获取的情况,本文就此情况给出完整的解决方案

原因分析

@Anysc注解会开启一个新的线程,主线程的Request和子线程是不共享的,所以获取为null

在使用springboot的自定带的线程共享后,代码如下,Request不为null,但是偶发的其中body/head/urlparam内容出现获取不到的情况,是因为异步任务在未执行完毕的情况下,主线程已经返回,拷贝共享的Request对象数据被清空

java 复制代码
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//设置子线程共享
RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
HttpServletRequest request = servletRequestAttributes.getRequest();

解决方案

前置条件

启动类添加@EnableAsync注解
标记@Async的异步方法不能和调用者在同一个class中

pom配置

java 复制代码
<!-- 阿里线程共享 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.11.0</version>
        </dependency>

requrest共享

通过TransmittableThreadLocal对象进行线程对象共享

java 复制代码
public class CommonUtil {
    public static TransmittableThreadLocal<HttpServletRequest> requestTransmittableThreadLocal = new TransmittableThreadLocal<HttpServletRequest>();

    public static void shareRequest(HttpServletRequest request){
        requestTransmittableThreadLocal.set(request);
    }

    public static HttpServletRequest getRequest(){
        HttpServletRequest request = requestTransmittableThreadLocal.get();
        if(request!=null){
            return requestTransmittableThreadLocal.get();
        }else{
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes!=null){
                return  requestAttributes.getRequest();
            }else{
                return  null;
            }
        }
    }

    public static void remove(){
        requestTransmittableThreadLocal.remove();
    }
}

:系统中所有Request获取需要统一从CommonUtil指定来源,例如token鉴权等

自定义request过滤器

通过自定义过滤器对Request的内容进行备份保存,主线程结束时Request清除结束不会影响到子线程的相应参数的获取,也适用于增加拦截器/过滤器后body参数无法重复获取的问题。需要注意的是对header参数处理时key要忽略大小写
java 复制代码
public class HttpServletRequestReplacedFilter implements Filter, Ordered {
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) request);
        }
        //获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。
        // 在chain.doFiler方法中传递新的request对象
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public int getOrder() {
        return 10;
    }
}


public class RequestWrapper extends HttpServletRequestWrapper{

    private final byte[] body;
    private final HashMap<String,String> headMap;
    private final HashMap<String,String> requestParamMap;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = CommonUtil.getBodyString(request).getBytes(Charset.forName("UTF-8"));

        headMap = new HashMap();
        Enumeration<String> headNameList = request.getHeaderNames();
        while (headNameList.hasMoreElements()){
            String key = headNameList.nextElement();
            headMap.put(key.toLowerCase(),request.getHeader(key));
        }

        requestParamMap = new HashMap<>();
        Enumeration<String> parameterNameList = request.getParameterNames();
        while (parameterNameList.hasMoreElements()){
            String key = parameterNameList.nextElement();
            requestParamMap.put(key,request.getParameter(key));
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public String getHeader(String name) {
        return headMap.get(name.toLowerCase());
    }

    @Override
    public String getParameter(String name) {
        return requestParamMap.get(name);
    }
}

自定义任务执行器

用于拦截异步任务执行,在任务执前统一进行Request共享操作,且可以定义多个,不影响原有的异步任务代码

java 复制代码
public class CustomTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        System.out.println("异步任务共享request");
        return () -> {
            try {
                CommonUtil.shareRequest(request);
                runnable.run();
            } finally {
                CommonUtil.remove();
            }
        };
    }
}


@Configuration
public class TaskExecutorConfig {

    @Bean()
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setAwaitTerminationSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Bean("shareTaskExecutor")
    public Executor hpTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("shareTaskExecutor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        // 增加 TaskDecorator 属性的配置
        executor.setTaskDecorator(new CustomTaskDecorator());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

调用示例

给@Anysc注解指定进行共享拦截的任务执行器即可

java 复制代码
@PostMapping("/testAsync")
    @ResponseBody
    public Object testAsync(@RequestBody Map<String, Object> params) throws Exception{
        Result result = Result.okResult();
        asyncUtil.executeAsync();
        return result;
    }

@Component
public class AsyncUtil {
    @Async("shareTaskExecutor")
    public void executeAsync () throws InterruptedException {
        System.out.println("开始执行executeAsync");
        Thread.sleep(3000);
        System.out.println("结束执行executeAsync");
    }
}
相关推荐
morris1312 分钟前
【SpringBoot】Xss的常见攻击方式与防御手段
java·spring boot·xss·csp
七星静香27 分钟前
laravel chunkById 分块查询 使用时的问题
java·前端·laravel
Jacob程序员28 分钟前
java导出word文件(手绘)
java·开发语言·word
ZHOUPUYU28 分钟前
IntelliJ IDEA超详细下载安装教程(附安装包)
java·ide·intellij-idea
stewie631 分钟前
在IDEA中使用Git
java·git
Elaine2023911 小时前
06 网络编程基础
java·网络
G丶AEOM1 小时前
分布式——BASE理论
java·分布式·八股
落落鱼20131 小时前
tp接口 入口文件 500 错误原因
java·开发语言
想要打 Acm 的小周同学呀1 小时前
LRU缓存算法
java·算法·缓存
镰刀出海1 小时前
Recyclerview缓存原理
java·开发语言·缓存·recyclerview·android面试