最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot詳細講解異步任務(wù)如何獲取HttpServletRequest

 更新時間:2022年04月25日 11:35:34   作者:code2roc  
在使用框架日常開發(fā)中需要在controller中進行一些異步操作減少請求時間,但是發(fā)現(xiàn)在使用@Anysc注解后會出現(xiàn)Request對象無法獲取的情況,本文就此情況給出完整的解決方案

原因分析

  • @Anysc注解會開啟一個新的線程,主線程的Request和子線程是不共享的,所以獲取為null
  • 在使用springboot的自定帶的線程共享后,代碼如下,Request不為null,但是偶發(fā)的其中body/head/urlparam內(nèi)容出現(xiàn)獲取不到的情況,是因為異步任務(wù)在未執(zhí)行完畢的情況下,主線程已經(jīng)返回,拷貝共享的Request對象數(shù)據(jù)被清空
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//設(shè)置子線程共享
RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
HttpServletRequest request = servletRequestAttributes.getRequest();

解決方案

前置條件

  • 啟動類添加@EnableAsync注解
  • 標(biāo)記@Async的異步方法不能和調(diào)用者在同一個class中

pom配置

        <!-- 阿里線程共享 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.11.0</version>
        </dependency>

requrest共享

通過TransmittableThreadLocal對象進行線程對象共享

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();
    }
}

注:系統(tǒng)中所有Request獲取需要統(tǒng)一從CommonUtil指定來源,例如token鑒權(quán)等

自定義request過濾器

通過自定義過濾器對Request的內(nèi)容進行備份保存,主線程結(jié)束時Request清除結(jié)束不會影響到子線程的相應(yīng)參數(shù)的獲取,也適用于增加攔截器/過濾器后body參數(shù)無法重復(fù)獲取的問題。需要注意的是對header參數(shù)處理時key要忽略大小寫

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);
        }
        //獲取請求中的流如何,將取出來的字符串,再次轉(zhuǎn)換成流,然后把它放入到新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);
    }
}

自定義任務(wù)執(zhí)行器

用于攔截異步任務(wù)執(zhí)行,在任務(wù)執(zhí)前統(tǒng)一進行Request共享操作,且可以定義多個,不影響原有的異步任務(wù)代碼

public class CustomTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        System.out.println("異步任務(wù)共享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;
    }
}

調(diào)用示例

給@Anysc注解指定進行共享攔截的任務(wù)執(zhí)行器即可

    @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("開始執(zhí)行executeAsync");
        Thread.sleep(3000);
        System.out.println("結(jié)束執(zhí)行executeAsync");
    }
}

到此這篇關(guān)于SpringBoot詳細講解異步任務(wù)如何獲取HttpServletRequest的文章就介紹到這了,更多相關(guān)SpringBoot獲取HttpServletRequest內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot項目集成Smart-Doc的實戰(zhàn)指南

    SpringBoot項目集成Smart-Doc的實戰(zhàn)指南

    Smart-Doc是一款強大的基于Java的API文檔生成工具,它通過對接口源代碼進行分析來生成全面而準確的文檔,完全不需要對代碼進行任何注入,下面我們看看如何在SpringBoot項目中集成Smart-Doc吧
    2025-10-10
  • SpringBoot啟動原理深入解析

    SpringBoot啟動原理深入解析

    我們開發(fā)任何一個Spring Boot項目都會用到啟動類,下面這篇文章主要給大家介紹了關(guān)于SpringBoot啟動原理解析的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-04-04
  • SpringBoot連接MYSQL數(shù)據(jù)庫并使用JPA進行操作

    SpringBoot連接MYSQL數(shù)據(jù)庫并使用JPA進行操作

    今天給大家介紹一下如何SpringBoot中連接Mysql數(shù)據(jù)庫,并使用JPA進行數(shù)據(jù)庫的相關(guān)操作。
    2017-04-04
  • SpringBoot自定義線程池,執(zhí)行定時任務(wù)方式

    SpringBoot自定義線程池,執(zhí)行定時任務(wù)方式

    這篇文章主要介紹了SpringBoot自定義線程池,執(zhí)行定時任務(wù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • mybatis?plus實現(xiàn)分頁邏輯刪除

    mybatis?plus實現(xiàn)分頁邏輯刪除

    這篇文章主要為大家介紹了mybatis?plus實現(xiàn)分頁邏輯刪除的方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • SpringBoot集成Kafka的實現(xiàn)示例

    SpringBoot集成Kafka的實現(xiàn)示例

    本文主要介紹了SpringBoot集成Kafka的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-01-01
  • Java?Map雙列集合使代碼更高效

    Java?Map雙列集合使代碼更高效

    這篇文章主要介紹了Java?Map雙列集合使用,使你的代碼更高效,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • Java中有什么工具可以進行代碼反編譯詳解

    Java中有什么工具可以進行代碼反編譯詳解

    這篇文章主要介紹了Java中有什么工具可以進行代碼反編譯的相關(guān)資,料,包括JD-GUI、CFR、Procyon、Fernflower、Javap、BytecodeViewer、Krakatau和JAD,每種工具都有其特點和適用場景,需要的朋友可以參考下
    2025-03-03
  • SpringCloud啟動eureka server后,沒報錯卻不能訪問管理頁面(404問題)

    SpringCloud啟動eureka server后,沒報錯卻不能訪問管理頁面(404問題)

    這篇文章主要介紹了SpringCloud啟動eureka server后,沒報錯卻不能訪問管理頁面(404問題),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • SpringBoot中YAML配置文件實例詳解

    SpringBoot中YAML配置文件實例詳解

    前面一直在使用properties配置文件,spring boot也支持yaml配置文件,下面這篇文章主要給大家介紹了關(guān)于SpringBoot中YAML配置文件的相關(guān)資料,需要的朋友可以參考下
    2023-04-04

最新評論

安丘市| 博客| 沂南县| 翁源县| 东乡县| 礼泉县| 保定市| 满洲里市| 东台市| 佛山市| 芜湖市| 阜阳市| 淮南市| 保德县| 类乌齐县| 米泉市| 景洪市| 志丹县| 皋兰县| 皮山县| 钟山县| 淅川县| 饶平县| 肥城市| 桦甸市| 林芝县| 昌邑市| 和硕县| 丹江口市| 顺义区| 荆州市| 长治市| 苍溪县| 南靖县| 南川市| 陵水| 崇州市| 康保县| 铜陵市| 当阳市| 冕宁县|