我有一个具有多个自定义ThreadPoolTaskExecutors
的以下类,在此示例中将与一个类一起显示。
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean(name = "streetCheckerExecutor")
public Executor getStreetAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setQueueCapacity(1000000);
executor.setThreadNamePrefix("streetCheckerExecutor-");
executor.initialize();
return executor;
}
}
我有一个下面的类,它从数据库中获取内容,我希望能够检查streetCheckerExecutor
的队列大小,如果它小于特定数目,则将内容添加到队列中
@Component
public class StreetChecker {
@Autowired
StreetRepository streetRepository;
@Autowired
StreetCheckService streetChecker;
@EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
try {
List<Street> streetList = streetRepository.getStreets();
for (int i = 0; i < streetList.size(); i++) {
streetChecker.run(streetList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("---------------------");
}
}
}
下面是工人阶级
@Component
public class StreetCheckService {
@Async("streetCheckerExecutor")
public void run(Content content) {
try {
//do work
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
我正在处理大量数据,我不想每次都从数据库中获取所有内容,但是我想检查streetCheckerExecutor
的队列大小,如果它小于数字,我想从数据库中获取更多内容并将其添加到streetCheckerExecutor
queque
下面是我想通过将上面的checkStreets
转换为下面的{1>}来实现的方法
@EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
while (true) {
try {
// check the queue size of streetCheckerExecutor
// if less than a number
// add to the queue
// else keep waiting and will try again in X minutes
} catch (Exception e) {
} finally {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
但是如何使用checkStreets()
方法获得队列的大小?
答案 0 :(得分:1)
您可以将自己的ThreadPoolTaskExecutor
自动布线,并使用getThreadPoolExecutor().getQueue()
获取队列。
@Autowire
@Qualifier("streetCheckerExecutor")
private Executor streetExecutor;
@EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
while (true) {
try {
final BlockingQueue<Runnable> queue = streetExecutor.getThreadPoolExecutor().getQueue();
if(queue.size() <= 5) {
queue.add(() -> {
final List<Street> streetList = streetRepository.getStreets();
streetList.forEach(street -> {
streetChecker.run(street);
});
});
}
} catch (Exception e) {
} finally {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我不确定这是您的意思,但是也许是这样。