spring 引导异步任务处理对象数组
spring boot asynctask to process object array
我有一个要求,我从 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.
您可以使用 Google 具有分区功能的 Guava:
Lists.partition(java.util.List, int)
我有一个要求,我从 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.
您可以使用 Google 具有分区功能的 Guava:
Lists.partition(java.util.List, int)