我有一个要求,因为我从http请求中获取对象列表,我需要响应202并安排我的对象数组进行平行处理。
@Configuration
@EnableAsync
public class AsyncConfiguration
{
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(1000);
executor.setThreadNamePrefix("AsynchThread-");
executor.initialize();
return executor;
}
}
@Service
public class AsyncService {
private static Logger log = LoggerFactory.getLogger(AsyncService.class);
@Async("asyncExecutor")
public void processEmpoyess(List<Employees> employees) throws InterruptedException
{
employees.forEach( item->{ log.info(item.name); try {
log.info("Going to sleep " + item.name);
Thread.sleep(10000); /* my business logic for each employee may take 5 to 10 seconds */
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } );
return ;
}
}
@RequestMapping(value = "/employeelistfull", method = RequestMethod.POST)
public void postAllEmployees(@RequestBody Employees employees) throws InterruptedException, ExecutionException
{
List<EmployeeAddress> listss = employees.getEmployeeList();
service.processEmpoyess(listss);
}
在我的示例中,我可能会有 1000 名员工,我想以 10 x 10 的速度处理,每个员工的业务逻辑可能需要 5 到 10 秒。
使用我上面的代码,它正在分配给异步任务,但异步任务正在一个接一个地执行。那么在这里我需要再创建一个异步任务并分配员工吗?还是异步任务有任何其他方法来处理列表?
在将列表发送到异步方法之前,您必须将列表拆分为块。在你的情况下 10.
你可以使用具有分区功能的谷歌番石榴:
Lists.partition(java.util.List, int)
https://guava.dev/releases/snapshot/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-