我配置了两个不同的线程池,一个用于@Scheduled
,另一个用于@Async
。但是,我注意到@Async
的线程池没有被使用。
以下是调度程序配置
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("my-sched-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
以下是异步配置
@Configuration
@EnableAsync
public class AppConfig {
@Bean(name = "asyncTaskExecutor")
public TaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(15);
executor.setMaxPoolSize(15);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("my-async-pool-");
executor.initialize();
return executor;
}
}
以下是我如何调用它们
@Scheduled(fixedRateString = "2000" )
public void schedule() {
log.debug("here is the message from schedule");
asyncMethod();
}
@Async("asyncTaskExecutor")
public void asyncMethod(){
log.info("here is the message from async");
}
以下是日志
{"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message from schedule"}
{"thread":"my-sched-pool-1","level":"INFO","description":"here is the message from async"}
您可以注意到,两个日志都具有该调度程序的相同池。但我希望看到第二个来自异步
答案 0 :(得分:6)
如果从相同的@Async
调用class
个方法,则会声明您实际上绕过了Spring的代理机制,这就是为什么您的示例无法正常工作的原因。尝试使用class
注释@Service
或任何其他@Component
类型的单独@Service
SomeScheduledClass {
private final SomeAsyncClass someAsyncClass;
public SomeScheduledClass(SomeAsyncClass someAsyncClass) {
this.someAsyncClass = someAsyncClass;
}
@Scheduled(fixedRateString = "2000" )
public void schedule() {
log.debug("here is the message from schedule");
someAsyncClass.asyncMethod();
}
}
@Service
SomeAsyncClass {
@Async("asyncTaskExecutor")
public void asyncMethod(){
log.info("here is the message from async");
}
}
来调用该方法。
class Superr {
int k;
int g;
int l;
Superr(int a, int b, int c) {
k = a;
g = b;
l = c;
}
void show() {
System.out.println("value of l" + l);
}
}
class Sub extends Superr {
int h;
Sub(int a, int b, int c, int d) {
e = a;
f = b;
g = c;
l = d;
}
class Main {
public static void main(String[] args) {
Superr b = new Super(1, 2, 3);
Sub c = new Sub(1, 2, 3, 4);
}