哪个 TaskExecutor 用于异步日志记录?

Which TaskExecutor to use for async logging?

我有一个 REST 网络服务,想记录所有传入和传出的 XML 请求。 由于它们可能非常大,而且我还必须应用某种转换,所以我想在异步线程中执行它。

到目前为止,我只是在记录器方法上使用 @Async 注释。这将使用默认值 SimpleAsyncTaskExecutor,即 "does not reuse any threads": https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#scheduling-task-executor-types

问题:我是否应该更好地定义自己的 ThreadPoolTaskExecutor 而不是依赖默认的简单执行程序?为短期日志记录任务设置一个 "reusing threads" 执行程序是否明智?

进一步考虑:我还将进行一些异步数据库行更新,这些更新也应该使用 @Async 执行,并且可能使用相同的执行程序。

我的主要问题是:我不想考虑固定的线程池大小、容量、节流限制等。我只想告诉我的例程:"Execute the following logic in an async thread." 只需在上面堆放任何东西.

我必须使用 TaskExecutors 中的哪一个,应该应用哪个配置?

下面的执行者是否合适?

@Bean
public ThreadPoolTaskExecutor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(4);
    return executor;
}

ThreadPoolTask​​Executor 适合您的问题。 例如

should I better define my own ThreadPoolTaskExecutor rather than relying on the default simple executor?

使用默认 ThreadPoolTaskExecutor 除非您需要对其进行自定义。

Would it be wise to have a "reusing threads" executor for the short-lived logging tasks?

是的。

I don't want to think about a fixed pool size of threads, capacity, throttle limits etc. I just want to tell my routine: "Execute the following logic in an async thread." And just stack anything on it.

Which of the TaskExecutors would I have to use for it, and which configuration should be applied?

ThreadPoolTaskExecutor 就够了。在您的示例代码中将池大小设置为 Runtime.getRuntime().availableProcessors()