【发布时间】:2019-06-18 03:39:16
【问题描述】:
我正在尝试创建一个 Spring Boot 应用程序,我需要从数据库中获取记录并为从数据库中获取的每条记录调用 REST API。但是,我不想一次获取所有记录,而是想批量检索,比如 10 个,让其余的调用它们,然后再获取 10 个并做同样的事情,直到最后一条记录。我正在使用 spring-data-jpa。我怎样才能做到这一点?
P.S.:它是一个多线程调用,数据库是 Amazon DynamoDB
到目前为止我的代码:
控制器:
//Multi Threaded Call to rest
@GetMapping("/myApp-multithread")
public String getQuoteOnSepThread() throws InterruptedException, ExecutionException {
System.out.println("#################################################Multi Threaded Post Call######################");
ExecutorService executor= Executors.newFixedThreadPool(10);
List<Future<String>> myFutureList= new ArrayList<Future<String>>();
long startTime=System.currentTimeMillis()/1000;
***//Here instead of fetching and calling Mycallable for each one, I want
// to do it in batches of 10***
Iterable<Customer> customerIterable=repo.findAll();
List<Customer> customers=new ArrayList<Customer>();
customerIterable.forEach(customers::add);
for(Customer c:customers) {
MyCallable myCallable= new MyCallable(restTemplate, c);
Future<String> future= executor.submit(myCallable);
myFutureList.add(future);
}
for(Future<String> fut:myFutureList) {
fut.get();
}
executor.shutdown();
long timeElapsed= (System.currentTimeMillis()/1000)-startTime;
System.out.println("->>>>>>>>>>>>>>>Time Elapsed In Multi Threaded Post Call<<<<<<<<<<<<<<<-"+timeElapsed);
return "Success";
}
我的可调用对象:
@Scope("prototype")
@Component
public class MyCallable implements Callable<String>{
private RestTemplate restTemplate;
private Customer c;
public MyCallable(RestTemplate rt, Customer cust) {
this.restTemplate = rt;
this.c = cust;
}
@Override
public String call() throws Exception {
System.out.println("Customer no"+ c.getId() +"On thread Number"+Thread.currentThread().getId());
restTemplate.postForObject("http://localhost:3000/save", c, String.class);
return "Done";
}
}
我怎样才能做到这一点?
【问题讨论】:
-
如果您“使用 JPA”,请发布一些实际的 JPA API 代码,例如您在哪里进行查询
-
不,比利,我正在使用 spring-data-jpa。我已经更新了这个问题。如果您有任何解决方案,请帮助
标签: spring-boot spring-data-jpa spring-data amazon-dynamodb