尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

Spring注解--@Async异步执行的方法

发布时间:2026/9/26 15:36:56

资讯中心
01
ARTICLE

Spring注解--@Async异步执行的方法

Spring注解--@Async异步执行的方法
原文网址Spring注解--Async异步执行的方法-CSDN博客简介本文介绍Spring的Async的用法。Async是用来异步执行任务的。基础代码正常情况下执行两个任务是这样的Controllerpackage com.knife.example.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; Slf4j Api(tags 测试) RequestMapping(test) RestController public class HelloController { Autowired private HelloService helloService; ApiOperation(测试1) PostMapping(test1) public void test() { helloService.task1(); helloService.task2(); } }Servicepackage com.knife.example.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; Slf4j Component public class HelloService { public void task1() { log.info(开始任务1); long start System.currentTimeMillis(); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } long end System.currentTimeMillis(); log.info(完成任务1耗时 (end - start) 毫秒); } public void task2() { log.info(开始任务2); long start System.currentTimeMillis(); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } long end System.currentTimeMillis(); log.info(完成任务2耗时 (end - start) 毫秒); } }它的结果是是顺序执行的。2024-07-07 15:53:00.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 开始任务1 2024-07-07 15:53:03.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 完成任务1耗时3000毫秒 2024-07-07 15:53:03.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 开始任务2 2024-07-07 15:53:06.073 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 完成任务2耗时3006毫秒使用异步加快速度假如上边task1和task2是不相关的那完全可以同时运行加快速度下边就用异步来做1.启用异步EnableAsync在启动类上加EnableAsyncpackage com.knife.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; EnableAsync SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }2.将方法标记为Async为便于维护全文已转移到此网址Spring-Async异步执行的方法 - 自学精灵
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

◈

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

◐

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

▲

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。