SpringBoot使用@Async异步多线程执行

SpringBoot使用@Async异步多线程执行

第一次使用,也采了好多坑,这里记录下。

在方法上加上@Async注解,不起作用时检查下面几点:

  • 调用者和@Async注解使用的方法在一个类中时候不起作用,原因是这个注解需要经过代理对象进行调用才有效(我的解决办法:分开放在不同的类中)。

  • 在启动类上开启注解,也就是在启动类xxxApplication.java 上加上注解@EnableAsync

  • 在这里插入图片描述

  • 使用@Async注解的方法归结为两种:没有返回值,有返回值(返回值类型必须是Future<xxxx>类型,return new AsyncResult<>(xxxx);)

1、无返回值

比较简单,在方法上加上和@Async注解即可,有线程池方法的在后面括号中写上线程池方法名(@Async(“myAsync”)),不要忘了在启动类上加上注解@EnableAsync。

下面是一个练习小Demo

/** 
* 任务类:没有配置线程池
*/
@Component
@Slf4j
public class TaskDemo {
    @Async
    public void test1() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时1500
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }       
    }

    @Async
    public void test2() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时200
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void test3() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时400
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void test4() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时900
            Thread.sleep(900);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void test5() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时1000
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

其他类中调用

private TaskDemo taskDemo;

    @GetMapping("/get")
    public void get() {
        log.info("开始");
        long begin = System.currentTimeMillis();
        try {
            taskDemo.test1();
            taskDemo.test2();
            taskDemo.test3();
            taskDemo.test4();
            taskDemo.test5();           
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        log.info("任务完成:耗时{}", System.currentTimeMillis() - begin);
    }

    @Autowired
    public void setTaskDemo(TaskDemo taskDemo) {
        this.taskDemo = taskDemo;
    }

结果:任务完成:耗时1519

2、有返回值

注意:如果有返回值时候,返回值一定是Future<xxx>

/** 
* 任务类:没有配置线程池
*/
@Component
@Slf4j
public class TaskDemo {
    @Async
    public Future<Integer> test1() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时1500
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(1500);
    }

    @Async
    public Future<Integer> test2() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时200
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(200);
    }

    @Async
    public Future<Integer> test3() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时400
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(400);
    }

    @Async
    public Future<Integer> test4() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时900
            Thread.sleep(900);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(900);
    }

    @Async
    public Future<Integer> test5() {
        String name = Thread.currentThread().getName();
        log.info("线程名称:" + name);
        try {
            // 模拟一系列数据操作,耗时1000
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(1000);
    }
}

调用类

private TaskDemo taskDemo;

    @GetMapping("/get")
    public void get() {
        log.info("开始");
        long begin = System.currentTimeMillis();
        try {
            Future<Integer> test1 = taskDemo.test1();
            Future<Integer> test2 = taskDemo.test2();
            Future<Integer> test3 = taskDemo.test3();
            Future<Integer> test4 = taskDemo.test4();
            Future<Integer> test5 = taskDemo.test5();

            Integer integer1 = 0;
            Integer integer2 = 0;
            Integer integer3 = 0;
            Integer integer4 = 0;
            Integer integer5 = 0;

            // 等待其他线程执行完毕,任务没有执行结束就一直等待,可以设置get的超时时间
            // test1.get(60, TimeUnit.SECONDS); // 设置超时时间,时间单位是秒
            // .isDone() 是判断线程执行完毕的标志,执行完毕返回true
            while (true){
                boolean done1 = test1.isDone();
                boolean done2 = test1.isDone();
                boolean done3 = test1.isDone();
                boolean done4 = test1.isDone();
                boolean done5 = test1.isDone();

                boolean b = done1 & done2 & done3 & done4 & done5;
                if (b){
                    // .get()方法获取线程执行结果,具有阻塞状态,所以需要死循环进行判断
                    integer1 = test1.get();
                    integer2 = test2.get();
                    integer3 = test3.get();
                    integer4 = test4.get();
                    integer5 = test5.get();
                    break;
                }
            }
            int i = integer1 + integer2 + integer3 + integer4 + integer5;
            log.info(i + "$");// 执行结果
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        log.info("统计完成:耗时{}", System.currentTimeMillis() - begin);
    }

    @Autowired
    public void setTaskDemo(TaskDemo taskDemo) {
        this.taskDemo = taskDemo;
    }

结果:
在这里插入图片描述

没有使用多线程之前执行的结果:
在这里插入图片描述

可以看到,执行时间减少了很多!欢迎留言讨论哦!

### Spring Boot 中使用 `@Async` 实现异步方法的最佳实践 #### 1. 开启异步功能 为了使 `@Async` 注解生效,需要在应用程序的主类或者配置类上添加 `@EnableAsync` 注解。这一步是必要的,因为只有启用该注解后,Spring 才会识别并管理带有 `@Async` 的方法。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } } ``` 此部分的操作已在多个引用中提及[^2][^4]。 --- #### 2. 定义异步方法 任何希望被异步执行的方法都可以加上 `@Async` 注解。需要注意的是,默认情况下,这些方法会被放入由 Spring 创建的线程池中运行。 ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { @Async public void executeAsyncTask() { System.out.println("任务正在异步执行..."); } @Async public Future<String> executeAsyncWithResult() throws InterruptedException { Thread.sleep(2000); // 模拟耗操作 return new AsyncResult<>("异步返回结果"); } } ``` 上述代码展示了两种常见的场景:一种是没有返回值的任务;另一种是有返回值的任务,并且可以通过 `Future` 对象获取其结果[^3]。 --- #### 3. 自定义线程池 虽然 Spring 默认提供了一个简单的线程池用于异步任务调度,但在实际生产环境中更推荐自定义线程池以满足特定需求。可以借助 `ThreadPoolTaskExecutor` 来完成这一目标: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean(name = "taskExecutor") public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); // 核心线程数 executor.setMaxPoolSize(10); // 最大线程数 executor.setQueueCapacity(25); // 队列容量 executor.initialize(); // 初始化线程池 return executor; } } ``` 通过这种方式,我们可以精确控制线程的数量及其行为模式,从而优化系统的性能表现[^1]。 --- #### 4. 超处理机制 当某些异步任务可能长间未响应,我们需要为其设定合理的超策略以防阻塞资源。下面是一个基于 `CompletableFuture` 的例子展示如何实现这一点: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public String callWithTimeout(int timeoutInSeconds) throws ExecutionException, TimeoutException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(timeoutInSeconds * 1000L); // 模拟延迟 } catch (InterruptedException e) { throw new RuntimeException(e); } return "成功"; }, taskExecutor()); return future.get(timeoutInSeconds / 2, TimeUnit.SECONDS); // 设置一半间为超限 } ``` 这里利用了 Java 提供的高级 API —— `CompletableFuture` 和它的 `get(long timeout, TimeUnit unit)` 方法来简化超逻辑的设计。 --- #### 总结 以上就是关于如何在 Spring Boot 应用程序中有效运用 `@Async` 进行异步编程的一些最佳实践建议。合理调整线程池参数以及引入适当的错误恢复手段都是构建健壮服务不可或缺的部分。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值