springboot使controller异步调用

调用controller方法,遇到操作时间很长的情况下,不希望前端一直等待操作,而希望前端立马接收到操作启动的反馈,而真正的操作在后端执行,需要用到异步调用的方法。实现步骤如下:

一、配置异步支持: 首先,在应用程序的主类上添加 @EnableAsync 注解,以启用异步支持

复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
 
//@EnableAsync
@SpringBootApplication
@EnableAsync
public class MyApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

二、在ExportService的方法exportCsv上增加注解 @Async声明该方法是异步方法

复制代码
@Service
public class ExportService {
   
    /**
     * 导出路径。
     *
     * @param path 参数说明
     * @return String
     */
    //如下注解 支持异步执行
    @Async
    public String exportCsv(String path) {
	     // 这里是需要异步执行的代码
	}
}

三、Controller类上调用异步方法,立马返回"导出操作在后台执行!请耐心等待!",导出进程在后端异步执行

复制代码
@RestController
@RequestMapping("/transfer")
public class ImportController extends BaseController {
	@Autowired
    private ExportService exportService;
	
	/**
     * 联机导出的数据。
     *
     * @param path 参数说明
     * @return AjaxResult
     */
    @PostMapping(value = "/exportCsv")
    @ResponseBody
    public AjaxResult ljExportCsv(@Valid String path) {
        exportService.exportCsv(path);
        return "导出操作在后台执行!请耐心等待!" ;
    }
}
相关推荐
阿拉斯攀登1 天前
电子签名:SpringBoot + 汉王 ESP560 的考核签名项目实施方案
springboot·canvas·电子签名·电子签·汉王
invicinble1 天前
对于认识IT系统的流量,服务器承载能力
springboot
wasteland~2 天前
Spring AI实战:SpringBoot项目结合Spring AI开发——Tool Calling(工具调用)详解与实战
springboot·工具调用·spring ai·tool calling
hopsky2 天前
Spring Boot多模块项目中程序可运行但mvn install 时找不到类
maven·springboot
原来是好奇心2 天前
深入Spring Boot源码(六):Actuator端点与监控机制深度解析
java·开发语言·源码·springboot
汝生淮南吾在北2 天前
SpringBoot3+Vue3小区物业报修系统+微信小程序
微信小程序·小程序·vue·毕业设计·springboot·课程设计·毕设
阿拉斯攀登2 天前
Spring Boot ——入门与实战
spring boot·springboot
她说..2 天前
Spring AOP场景4——事务管理(源码分析)
java·数据库·spring boot·后端·sql·spring·springboot
原来是好奇心2 天前
深入Spring Boot源码(八):高级特性与扩展点深度解析
java·源码·springboot
她说..2 天前
手机验证码功能实现(附带源码)
java·开发语言·spring boot·spring·java-ee·springboot