亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

提供文件時“無法在沒有 AsyncContext 的情況下調度”

提供文件時“無法在沒有 AsyncContext 的情況下調度”

LEATH 2021-09-12 15:30:26
我需要在“文件下載控制器”之上編寫一個“一次性文件下載”MVC 控制器。一旦文件被傳輸到客戶端,它必須從服務器中刪除。最初,編寫代碼是為了提供文件導入 org.springframework.core.io.Resource@GetMapping("/get/{someParam}")public ResponseEntity<Resource> downloadFile(Long someParam){    Long fileId = identify(someParam);    return super.downloadFile(fileId); //This uses a "File repository" service binding file IDs to physical paths}protected ResponseEntity<Resource> downloadFile(Long fileId){    File theFile = resolve(fileId);    return new FileSystemResource(theFile);}由于 ResponseEntity 是某種“未來”實體,我無法在 finally 塊中刪除該文件,因為它還不會被提供。所以我首先編寫了一個異步版本的文件下載,利用 Commons IO 來復制有效負載。然后我利用回調來僅從我的方法中處理文件。protected WebAsyncTask<Void> downloadFileAsync(Long fileId,HttpResponse response){ //API method for multiple uses across the application    InputStream is = new FileInputStream(resolve(fileId));    Callable<Void> ret = () -> {        IOUtils.copy(is,response.getOutputStream());        is.close();        return null;    };    return ret;}@GetMapping("/get/{someParam}")public WebAsyncTask<Void> downloadFile(Long someParam,HttpResponse response){    Long fileId = identify(someParam);    WebAsyncTask ret = downloadFileAsync(fileId,response);    ret.onCompletion(()-> fileService.delete(fileId)); //Here I leverage the callback because this file, in this point, is disposable    return ret;}我已將所有 servlet 和過濾器配置為在我的web.xml. 我做了一些研究,這個答案沒有幫助,因為我使用的是較新的 Tomcat 版本。我的代碼有什么問題?我沒有完全發布它以保持簡單,但是調試我看到寫操作成功并具有正確的有效負載。
查看完整描述

2 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我有同樣的問題。就我而言,解決方案是配置一個AsyncTaskExecutor:


@Configuration

public class WebConfig extends WebMvcConfigurerAdapter {


    @Override

    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {

        configurer.setDefaultTimeout(-1);

        configurer.setTaskExecutor(asyncTaskExecutor());

    }


    @Bean

    public AsyncTaskExecutor asyncTaskExecutor() {

        // an implementaiton of AsyncTaskExecutor

        return new SimpleAsyncTaskExecutor("async");

    }


}


查看完整回答
反對 回復 2021-09-12
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

根據@MDenium 的評論

不要使用供內部使用的 WebAsyncTask。只需使用 CompletableFuture 或返回 Callable。如果您將 try/finally 放在 Callable 中,它將起作用

WebAsyncTask 只是不是一個 API,因此當您從 MVC 方法返回時,Spring 不知道如何處理它。這不是執行異步執行的正確方法。它僅在內部用于承載任務和上下文。

Spring MVC 支持:

  • 延遲結果

  • 可調用

  • 可完成的未來

大概一個少數


查看完整回答
反對 回復 2021-09-12
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號