我的要求是从 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 秒。
使用我上面的代码,它分配给异步任务,但异步任务正在一项一项执行。那么在这里我需要再创建一个 Async 任务并分配员工吗?还是异步任务有任何其他方式来处理列表?