SpringBoot异步任务(2)|(线程池使用)

╰+哭是因爲堅強的太久メ 2023-10-14 16:24 141阅读 0赞

SpringBoot异步任务(2)|(线程池使用)


文章目录 SpringBoot异步任务(2)|(线程池使用) @[TOC] 前言 一、使用场景 二、springboot添加异步任务 1.配置线程池 2.线程池的使用 总结

章节
第一章链接: SpringBoot异步任务(1)|(异步任务执行以及回调)

前言

线程池开启异步任务在springboot中的使用

一、使用场景

项目中有一个批量调度的任务,客户上传批量的文章,让后将这些文章去进行任务处理

二、springboot添加异步任务

1.配置线程池

在springboot容器中配置线程池,后续使用直接将bean注入使用即可

  1. @Configuration
  2. @EnableAsync
  3. public class ExecutorEmbPoolConfig {
  4. private static final Logger logger = LoggerFactory.getLogger(ExecutorEmbPoolConfig.class);
  5. @Value("${embedding.pool.corePoolSize:20}")
  6. private int corePoolSize = 20;
  7. @Value("${embedding.pool.maxPoolSize:20}")
  8. private int maxPoolSize = 20;
  9. @Value("${embedding.pool.queueCapacity:100000}")
  10. private int queueCapacity = 100000;
  11. private String namePrefix = "embedding-service-";
  12. @Bean(name = "embeddingServiceExecutor")
  13. public ThreadPoolTaskExecutor asyncServiceExecutor() {
  14. logger.debug("start embedding embeddingServiceExecutor");
  15. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  16. //配置核心线程数
  17. executor.setCorePoolSize(corePoolSize);
  18. //配置最大线程数
  19. executor.setMaxPoolSize(maxPoolSize);
  20. //配置队列大小
  21. executor.setQueueCapacity(queueCapacity);
  22. //配置线程池中的线程的名称前缀
  23. executor.setThreadNamePrefix(namePrefix);
  24. // 允许回收核心线程
  25. executor.setAllowCoreThreadTimeOut(true);
  26. // CALLER_RUNS: 不在新线程中执行任务,而是有调用者所在的线程来执行
  27. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  28. //执行初始化
  29. executor.initialize();
  30. return executor;
  31. }
  32. }

2.线程池的使用

  1. @Resource(name = "embeddingServiceExecutor")
  2. private ThreadPoolTaskExecutor executor;
  3. @Scheduled(cron = "0/30 * * * * ?")
  4. public void FileToMilvesJob() {
  5. //定义计数器
  6. List<DocumentMilvusRecord> documentMilvusRecords = recordService.findByStatus(RecordStatus.WAIT);
  7. if (CollectionUtils.isEmpty(documentMilvusRecords)) {
  8. return;
  9. }
  10. List<DocumentMilvusRecord> excuteList;
  11. if (documentMilvusRecords.size() > 50) {
  12. excuteList = documentMilvusRecords.subList(0, 50);
  13. } else {
  14. excuteList = documentMilvusRecords;
  15. }
  16. log.info("本次任务需要执行任务“{}条", excuteList.size());
  17. for (DocumentMilvusRecord record : excuteList) {
  18. recordService.updateRecordStatus(record);
  19. executor.execute(() -> {
  20. try {
  21. docEmbeddingCreate(record); // 执行业务逻辑
  22. } catch (Exception e) {
  23. log.error(e.getMessage());
  24. }
  25. });
  26. }
  27. }

总结

上面的方式实现了自定义一个线程池,然后执行任务的时候获取线程池并执行任务。

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读