springmvc異步處理


 

好久沒有寫過博客了,都是看大牛的文章,略過~~

突然感覺成長在於總結!廢話不多說,開干

由於是公司項目,所以不方便給出代碼,看圖操作

在項目util目錄下創建工具類TaskExecutorConfig 並且實現 org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

該工具類用@EnableAsync修飾,表示可以用於異步;並且要實現

getAsyncExecutor()方法和
getAsyncUncaughtExceptionHandler()方法;在
getAsyncExecutor()內創建線程池並返回調用;

在需要異步調用的地方創建異步類TaskExecutorConfig並調用它的getAsyncExecutor()方法,得到線程池java.util.concurrent.

Executor對象;再通過Executor.execute(new MyRunnable(mapParam))實現異步;MyRunnable是我創建的內部類

public static class MyRunnable implements Runnable {
private Map<String,Object> mapParam;
public MyRunnable(Map<String,Object> mapParam){
this.mapParam = mapParam;
}
/**
* 重寫run方法
*/
@Override
public void run() {
concertVideo(mapParam);
}
}
需要注意的是Executor在java.util.concurrent中;

如果這樣不行可以再試試用@ComponentScan("com.videoadmin.async")修飾異步類TaskExecutorConfig;再通過以下方式實現異步:
               AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
TaskService taskService = context.getBean(TaskService.class);
taskService.doAsync(destFile,objectId);
// 這里調用異步方法...
context.close();
@Service
public class TaskService {
private static String piantouTs = "F:\\shiping_test\\tsFile\\test\\2.ts";
@Async
public String doAsync(String filePath,String objectId) throws Exception {
if (filePath != null) {
filePath = ConvertVideo.transTOts(filePath);
if (filePath != null) {
filePath = ConvertVideo.concatVideo(piantouTs, filePath);
if (filePath != null) {
filePath = ConvertVideo.processMp4(filePath);
if (filePath != null) {
return filePath;
}
}
}
}
return null;
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM