使用spring的@Async异步执行方法

青旅半醒 2022-07-17 00:44 390阅读 0赞

应用场景:

1、某些耗时较长的而用户不需要等待该方法的处理结果

2、某些耗时较长的方法,后面的程序不需要用到这个方法的处理结果时

在spring的配置文件中加入对异步执行的支持

复制代码

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xmlns:task="http://www.springframework.org/schema/task"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  12. http://www.springframework.org/schema/context
  13. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  14. http://www.springframework.org/schema/mvc
  15. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  16. http://www.springframework.org/schema/task
  17. http://www.springframework.org/schema/task/spring-task-4.0.xsd">
  18. <context:annotation-config />
  19. <!--扫描注解 -->
  20. <context:component-scan base-package="com.tf" />
  21. <!-- 支持异步方法执行 -->
  22. <task:annotation-driven />

复制代码

使用方法

复制代码

  1. import org.springframework.scheduling.annotation.Async;
  2. public class Test {
  3. @Async
  4. public static void testAsyncMethod(){
  5. try {
  6. //让程序暂停100秒,相当于执行一个很耗时的任务
  7. Thread.sleep(100000);
  8. } catch (InterruptedException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. }
  13. }

复制代码

调用方法

  1. public static void main(String[] args) {
  2. Test.testAsyncMethod();
  3. System.out.println("我已经执行了!");
  4. }

发表评论

表情:
评论列表 (有 0 条评论,390人围观)

还没有评论,来说两句吧...

相关阅读