spring boot 中的异步@Async

spring boot 开启异步调用

1、启动类上添加@EnableAsync注解,表示启动异步

2、在具体实现异步的方法上添加@Async注解

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
package com.example.demo;


import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Description: TODO
 * @author: sl
 * @date: 2024年05月30日 21:55
 */
@Component
public class DemoController {

     /**
     *  Async相当于是方法级别的线程,本身没有自定义线程池更加灵活
     *  相当于是每进来一个请求就开启一个线程,超过核心线程数小于最大线程数放入队列,
     *  队列满了,继续创建线程直至达到最大线程数
     * @throws InterruptedException
     */
    @Async
    public void testSync() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("异步执行成功");
    }
}

测试执行 

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private DemoController demoController;

    @Test
    void contextLoads() throws InterruptedException {
        demoController.testSync();
        System.out.println("主线程执行");
        Thread.sleep(4000);
    }

}

执行结果 

执行原理

SpringBoot会默创建了一个线程池,使用这里面的线程来执行异步调用,在项目中使用

手动创建线程池异步调用 

常用线程池创建以及弊端

Executors 是一个 Java 中的工具类。提供四种线程池创建方式,工厂方法来创建不同类型的线程池。Executors 的创建线程池的方法,创建出来的线程池都实现了ExecutorService 接口,

1.newFiexedThreadPool(int Threads):创建固定数目线程的线程池。
2.newCachedThreadPool():创建一个可缓存的线程池,调用 execute将重用以前构造的线程(如果线程可用)。如果没有可用的线程,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
3.newSingleThreadExecutor() 创建一个单线程化的 Executor。
4.newScheduledThreadPool(int corePoolSize) 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代 Timer 类

不建议大家使用Executors这个类来创建线程池呢,阿里开发手册这样定义:
强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式

Executors 返回的线程池对象的弊端如下:

1) FixedThreadPool 和 SingleThreadPool:

允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM

2) CachedThreadPool 和 ScheduledThreadPool:

允许的创建线程数量为 Integer.MAX_VALUE, 可能会创建大量的线程,从而导致 OOM

使用常见的三种线程池创建方式,单一、可变、定长都有一定问题,原因是 FixedThreadPool 和 SingleThreadExecutor 底层都是用LinkedBlockingQueue 实现的,这个队列最大长度为 Integer.MAX_VALUE,容易导致 OOM
所以实际生产一般自己通过 ThreadPoolExecutor 的 7 个参数,自定义线程池

spring boot创建线程池 

springboot创建线程池,Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,直接使用注解启用。
Async相当于是方法级别的线程,本身没有自定义线程池更加灵活

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: TODO
 * @author: sl
 * @date: 2024年05月30日 22:37
 */
@Configuration
public class MyPoolConfig {
    @Bean
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //设置最大线程数
        executor.setMaxPoolSize(15);
        //设置队列容量
        executor.setQueueCapacity(20);
        //设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        //设置默认线程名称
        executor.setThreadNamePrefix("1111-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

}

在Async中指定线程池

package com.example.demo;


import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Description: TODO
 * @author: sl
 * @date: 2024年05月30日 21:55
 */
@Component
public class DemoController {

    /**
     *  Async相当于是方法级别的线程,本身没有自定义线程池更加灵活
     *  相当于是每进来一个请求就开启一个线程,超过核心线程数小于最大线程数放入队列,
     *  队列满了,继续创建线程直至达到最大线程数
     * @throws InterruptedException
     */
    @Async("taskExecutor")
    public void testSync() throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(2000);
        System.out.println("异步执行成功");
    }
}

执行结果:

相关推荐

  1. C#Async异常处理

    2024-06-07 13:20:07       47 阅读
  2. vueasync

    2024-06-07 13:20:07       26 阅读
  3. Spring Boot异步线程池@Async

    2024-06-07 13:20:07       45 阅读
  4. Springboot Async 引起循环依赖

    2024-06-07 13:20:07       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 13:20:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 13:20:07       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 13:20:07       87 阅读
  4. Python语言-面向对象

    2024-06-07 13:20:07       96 阅读

热门阅读

  1. 安全通信网络

    2024-06-07 13:20:07       28 阅读
  2. 眼在手上的手眼标定(matlab+python)实测精度±1mm

    2024-06-07 13:20:07       19 阅读
  3. spring boot 白盒测试实战

    2024-06-07 13:20:07       28 阅读
  4. FPGA verilog入门案例笔记一

    2024-06-07 13:20:07       35 阅读
  5. Flask、uWSGI和Nginx在Web服务器架构中的职责

    2024-06-07 13:20:07       30 阅读
  6. 多云世界中的 API 治理

    2024-06-07 13:20:07       50 阅读
  7. Github 2024-06-04 Python开源项目日报 Top10

    2024-06-07 13:20:07       30 阅读
  8. 【路径规划】二维Dijkstra启发式改进算法

    2024-06-07 13:20:07       31 阅读
  9. LeetCode|938. Range Sum of BST

    2024-06-07 13:20:07       29 阅读
  10. 什么情况下需要进行网络安全等级保护?

    2024-06-07 13:20:07       32 阅读