春天启动背景工作

时间:2017-04-20 11:12:25

标签: spring-boot background thymeleaf

我正在使用Thymeleaf的Spring Boot。

当用户点击相关按钮时,它会发送post requst,并且在相关的控制器方法中有一个需要20分钟的功能。此函数不返回值。

我只想在后台处理这个功能。当应用程序到达此函数的行时,它应该向此函数发送参数并继续处理而不等待返回。

此案例的最佳做法是什么?

非常感谢提前。

更新

我的配置类

@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer{

@Bean(name = "ocrThread-")
public Executor threadPoolTaskExecutor() {
    return new ThreadPoolTaskExecutor();
}

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(10);
        executor.initialize();
        return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    // TODO Auto-generated method stub
    return null;
}

}

服务类

@Service
public class OcrService {

@Async
public String treadliOcr(List<String> liste, String kok) throws 
InterruptedException, IOException, TesseractException {


 .....

}

}

控制器

    @RequestMapping(value="/aktar", method= RequestMethod.POST)
public String aktar(@RequestParam("belgeAdi") String belgeAdi,
                    @RequestParam("evrakTurId") String evrakTurId,
                    @RequestParam("kategoriId") String kategoriId,
                    @RequestParam("belgeTurId") String belgeTurId,
                    @RequestParam("firmaId") String firmaId,
                    @RequestParam("projeId") String projeId,
                    @RequestParam("aciklama") String aciklama) throws InterruptedException, IOException, TesseractException{

    Integer b = null;
    Integer p = null;
    String klasor = getInitYol();
    String belgeOnAd =  belgeAdi.substring(0, 14);
    BelgeIsimleri belgeIsimleri = new BelgeIsimleri();
    List<String> seciliListe = belgeIsimleri.seciliBelgeleriFiltrele(klasor, belgeOnAd);

    for(String s:seciliListe){

        File file = new File (getInitYol()+s);
        if(file.renameTo(new File("D:\\Done\\"+s))){
            file.delete();
            System.out.println(s+"yi sildi");
        }           


    }



    OcrService ocr = new OcrService();
    String result=ocr.treadliOcr(seciliListe,getInitYol());
    System.out.println("Ocr dan döndü");


    Integer et = Integer.valueOf(evrakTurId);
    Integer k = Integer.valueOf(kategoriId);
    if(null==belgeTurId || "".equals(belgeTurId)){

    }else{
        b = Integer.valueOf(belgeTurId);
    }

    Integer f = Integer.valueOf(firmaId);
    if(null==projeId || "".equals(projeId)){


    }else{
        p = Integer.valueOf(projeId);
    }

    belgeRepo.save(new BelgeEntity(et,k ,b , f ,p ,aciklama, result,belgeOnAd));


    return "redirect:/verigiris";
}

1 个答案:

答案 0 :(得分:1)

Spring通过@Async@EnableAsync提供对异步方法执行的注释支持:https://spring.io/guides/gs/async-method/