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

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

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

原因分析

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

解決方案

前置條件

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

pom配置

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

requrest共享

通過TransmittableThreadLocal對(duì)象進(jìn)行線程對(duì)象共享

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過濾器

通過自定義過濾器對(duì)Request的內(nèi)容進(jìn)行備份保存,主線程結(jié)束時(shí)Request清除結(jié)束不會(huì)影響到子線程的相應(yīng)參數(shù)的獲取,也適用于增加攔截器/過濾器后body參數(shù)無法重復(fù)獲取的問題。需要注意的是對(duì)header參數(shù)處理時(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);
        }
        //獲取請(qǐng)求中的流如何,將取出來的字符串,再次轉(zhuǎn)換成流,然后把它放入到新request對(duì)象中。
        // 在chain.doFiler方法中傳遞新的request對(duì)象
        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)一進(jìn)行Request共享操作,且可以定義多個(gè),不影響原有的異步任務(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注解指定進(jìn)行共享攔截的任務(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詳細(xì)講解異步任務(wù)如何獲取HttpServletRequest的文章就介紹到這了,更多相關(guān)SpringBoot獲取HttpServletRequest內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

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

    SpringBoot啟動(dòng)原理深入解析

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

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

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

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

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

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

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

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

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

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

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

    Java中有什么工具可以進(jìn)行代碼反編譯詳解

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

    SpringCloud啟動(dòng)eureka server后,沒報(bào)錯(cuò)卻不能訪問管理頁(yè)面(404問題)

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

    SpringBoot中YAML配置文件實(shí)例詳解

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

最新評(píng)論

九龙县| 慈利县| 汝南县| 宜章县| 高阳县| 望城县| 克东县| 资溪县| 谢通门县| 安丘市| 佛教| 宣恩县| 田阳县| 祁连县| 睢宁县| 桦南县| 泌阳县| 修水县| 新邵县| 旬邑县| 三穗县| 桑日县| 兰州市| 玉树县| 巴彦淖尔市| 成都市| 集安市| 丽水市| 江西省| 秦皇岛市| 隆德县| 永靖县| 湄潭县| 社旗县| 大石桥市| 西城区| 陆河县| 丹凤县| 郯城县| 华池县| 上犹县|