Spring Boot使用@Async注解异步调用,自定义线程池

Spring Boot使用@Async注解异步调用,自定义线程池

1.先在主启动类上加@EnableAsync注解,表示开启 Spring 异步方法执行功能
2.新建AsyncTestService.java

public interface AsyncTestService {
     

    void test1();

    void test2();

}

3.新建AsyncTestSeviceImpl.java,要异步执行的方法在方法上面加@Async注解,value = “testExecutor”,testExecutor为线程池名

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

@Service
public class AsyncTestSeviceImpl implements AsyncTestService {
     

    @Override
    public void test1(){
     
        System.out.println("ThreadName:" + Thread.currentThread().getName());
        int i = 0;
        do {
     
            System.out.println("不是异步执行!"+i);
            i++;
        }while (i<10);
    }

    @Override
    @Async(value = "testExecutor")//testExecutor为线程池名
    public void test2() {
     
        System.out.println("ThreadName:" + Thread.currentThread().getName());
        int i = 0;
        do {
     
            System.out.println("异步执行!"+i);
            i++;
        }while (i<10);
    }
}

4.新建AsyncTestController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author shaosiyun
 * @version 1.0
 * @date 2020/12/9 10:31
 */
@RestController
public class AsyncTestController {
     

    @Autowired
    private AsyncTest asyncTest;

    @RequestMapping(value = "/asyncTest")
    public void test(){
     
        asyncTest.test1();
        asyncTest.test2();
    }

}

5.新建线程池配置类 PoolConfig.java


@Configuration
public class PoolConfig {
     

    @Bean("testExecutor")//线程池名
    public Executor testExecutor() {
     
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //线程池创建时候初始化的线程数
        executor.setCorePoolSize(10);
        //线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(20);
        //用来缓冲执行任务的队列
        executor.setQueueCapacity(200);
        //允许线程的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        //线程池名的前缀
        executor.setThreadNamePrefix("testExecutor-");
        //当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

启动程序访问/asyncTest接口,即可看到方法已经在异步执行。

你可能感兴趣的:(Spring Boot使用@Async注解异步调用,自定义线程池)