侧边栏壁纸
博主头像
高大北博主等级

所有的再见中,我最喜欢明天见

  • 累计撰写 208 篇文章
  • 累计创建 151 个标签
  • 累计收到 20 条评论
标签搜索

目 录CONTENT

文章目录

Springboot使用线程池demo

高大北
2022-05-05 / 0 评论 / 3 点赞 / 298 阅读 / 2,253 字 / 正在检测是否收录...

1、添加application.yml,设置数据

async:
  executor:
    ##核心线程数
    corePoolSize: 10
    ##最大线程数
    maxPoolSize: 10
    ##线程池中的线程的名称前缀
    prefix: async-
    ##队列大小
    queueCapacity: 10000

1、配置线程池配置类

创建一个线程池的配置,让Spring Boot加载,使用@Configuration和@EnableAsync这两个注解,表示这是线程池配置类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
​
@Configuration
@EnableAsync
public class AsyncPoolConfig {
​
    private static final Logger logger = LoggerFactory.getLogger(AsyncPoolConfig.class);
​
   @Value("${async.executor.corePoolSize}")
    private int corePoolSize;
    @Value("${async.executor.maxPoolSize}")
    private int maxPoolSize;
    @Value("${async.executor.queueCapacity}")
    private int queueCapacity;
    @Value("${async.executor.prefix}")
    private String prefix;
​
    @Bean(name = "asyncServiceAsyncPool")
    public Executor asyncServiceAsyncPool() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(prefix);
        
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2、创建异步调用接口以及实现类

public interface AsyncService {
    /**
     * 执行异步任务
     * 可以根据需求测试
     */
    void executeAsync();
}

实现类

@Service
public class AsyncServiceImpl implements AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    @Async("asyncServiceAsyncPool")
    public void executeAsync() {
        logger.info("start executeAsync");

        System.out.println("异步线程要做的事情");
        logger.info("end executeAsync");
    }
}

@Async(“asyncServiceExecutor”)表示指定使用asyncServiceExecutor线程池异步执行该方法,就是@Bean里边定义的名称

3、调用异步方法测试

创建Controller通过注解@Autowired注入这个Service

@Autowired
private AsyncService asyncService;

@GetMapping("/async")
public void async(){
    asyncService.executeAsync();
}
3

评论区