Spring中使用@Async让方法异步执行

Spring中使用@Async让方法异步执行

一、概述

​ 很多时候,为了提高性能我们都需要引入多线程来提高系统性能,说通俗点就是让方法异步执行。实现这个目的可以用执行异步方法的工具类,开个线程去执行。而在Spring中,则可以使用@Async注解,相比较工具类会更加优雅,本篇文章将会详细地介绍如何去使用

二、开启步骤

配置线程池

创建配置类ThreadPoolConfig.calss,异步方法最终会在这个线程池中被执行

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;
    }
}

yml文件中配置线程池属性

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

三、测试

测试类

编写接口

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

编写实现类

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

接着再自己编写一个类来调用此方法

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

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

猜你喜欢

转载自blog.csdn.net/weixin_44829930/article/details/122464484