讲讲springboot的@Async

Spring Boot的@Async注解用于表示一个方法是异步的,即该方法可以在一个独立的线程中执行,而不会阻塞当前线程。这对于处理一些耗时的操作非常有用,如发送电子邮件、生成报表、处理文件上传等。使用@Async注解可以提高应用程序的响应性和性能。

下面是使用@Async注解的一般步骤:

  1. 在Spring Boot应用程序的配置类上添加@EnableAsync注解,以启用异步方法的支持。这通常是在应用程序的主配置类上完成的。
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAsync
public class AsyncConfig {
    // 其他配置
}
  1. 在需要异步执行的方法上添加@Async注解。这个方法可以是在Spring Bean中定义的,也可以是在普通的类中定义的,只要它被Spring容器管理。
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Async
    public void asyncMethod() {
        // 异步执行的代码
    }
}
  1. 调用带有@Async注解的方法时,Spring会自动创建一个新的线程来执行该方法,而不会阻塞调用线程。
@Service
public class MyOtherService {

    @Autowired
    private MyService myService;

    public void doSomething() {
        // 调用异步方法
        myService.asyncMethod();

        // 继续执行其他操作,不会等待异步方法的完成
    }
}

为什么要给@Async自定义线程池?
使用@Async注解,在默认情况下用的是SimpleAsyncTaskExecutor线程池,该线程池不是真正意义上的线程池。
使用此线程池无法实现线程重用,每次调用都会新建一条线程。若系统中不断的创建线程,最终会导致系统占用内存过高,引发OutOfMemoryError错误

你可以在应用程序的配置中自定义线程池的属性,如最大线程数、队列大小等。

# application.properties
spring.task.execution.pool.core-size=10
spring.task.execution.pool.max-size=20

你可能感兴趣的:(#,后端面试题,#,Spring,spring,boot,后端,java)