Using @Async in Spring to execute methods asynchronously

Using @Async in Spring to execute methods asynchronously

I. Overview

​ Many times, in order to improve performance, we need to introduce multi-threading to improve system performance. The popular point is to let the method 异步执行. To achieve this purpose, you can use a tool class that executes asynchronous methods to open a thread to execute. In Spring, you can use @Asyncannotations, which are more elegant than tool classes. This article will introduce how to use them in detail.

Second, the opening steps

Configure thread pool

Create a configuration class ThreadPoolConfig.calss, the asynchronous method will eventually be executed in this thread pool

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置类
 * @author VernHe
 * @date 2021年12月31日 22:28
 */
@Getter
@Setter			// 因为是通过yml注入的,所以属性必须要有Setter
@Configuration	// 标记这是个配置类
@EnableAsync	// 使得@Async生效
@ConfigurationProperties(prefix = "task.pool")	// 读取yml配置文件中task.pool中的属性
public class ThreadPoolConfig {
    
    

    /**
     * 核心线程数(默认线程数)
     */
    private int corePoolSize;
    /**
     * 最大线程数
     */
    private int maxPoolSize;
    /**
     * 允许线程空闲时间(单位:默认为秒)
     */
    private int keepAliveSeconds;
    /**
     * 缓冲队列大小
     */
    private int queueCapacity;
    /**
     * 线程池名前缀
     */
    private String threadNamePrefix;

    /**
    * 往Spring容器中注册一个ThreadPoolTaskExecutor对象
    */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
    
    
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix(threadNamePrefix);
        return taskExecutor;
    }
}

Configure thread pool properties in the yml file

#线程池的配置
task:
  pool:
    corePoolSize: 5 #设置核心线程数
    maxPoolSize: 10  #设置最大线程数
    keepAliveSeconds: 300 #设置线程活跃时间(秒)
    queueCapacity: 50 #设置队列容量
    threadNamePrefix: thread-pool-service-

3. Test

test class

write interface

public interface AsyncService {
    
    
    /**
     * 异步方法
     */
    @Async	// 可以加在接口中的方法上或者实现类的方法上
    String testMethod();
}

Write the implementation class

@Service	// @Component注解也可以
public interface AsyncServiceImpl {
    
    
    /**
     * 异步方法
     */
    String testMethod();
}

Then write a class yourself to call this method

此处代码因为比较简单就省略了。

此处需要注意一下,一定要再编写一个类,然后调用这个AsyncService类中加了@Async的方法才能生效,
如果你在AsyncService类中写了一个没有加@Async的方法,去调用加了@Async的方法是不会生效的

Guess you like

Origin blog.csdn.net/weixin_44829930/article/details/122464484