Java: @Async异步线程池配置

java标志
image-3492

使用了Spring的@Async实现异步操作,需要自定义线程池.具体原因可自行搜索.

以下为线程池配置代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import lombok.Getter;
import lombok.Setter;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/*

配置参数(application.yaml):

# 异步调用自定义线程池配置.
async:
  core-pool-size: 32
  max-pool-size: 50
  queue-capacity: 100
  await-termination-seconds: 60
  keep-alive-seconds: 10

*/



@Configuration
@ConfigurationProperties(prefix = "async")
@Getter
@Setter
public class AsyncConfiguration implements AsyncConfigurer {

  private int corePoolSize;

  private int maxPoolSize;

  private int queueCapacity;

  private int awaitTerminationSeconds;

  private int keepAliveSeconds;

  @Bean("asyncExecutor")
  public ThreadPoolTaskExecutor executor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    var threadNamePrefix = "asyncExecutor-";
    executor.setThreadNamePrefix(threadNamePrefix);
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setAllowCoreThreadTimeOut(true);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
    executor.initialize();
    return executor;
  }

  @Override
  public Executor getAsyncExecutor() {
    return executor();
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return (ex, method, params) -> {
      ex.printStackTrace();
      /*log.error(
      "执行异步任务: 方法: {},方法参数: {},异常信息:{} ",
      method.getName(),
      method.getParameters(),
      ex.getMessage());*/

    };
  }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据