Вложенным исключением является java.util.concurrent.ExecutionException - PullRequest
0 голосов
/ 24 января 2019

Я новичок в многопоточности в Java и пытаюсь создать проект Spring с интерфейсом Callable и Future Class.

Я извлекаю все записи в динамо-базе данных, и для каждой записи я делаю многопоточный вызов внешней службе.

Но я получаю эту ошибку:

вложенным исключением является java.util.concurrent.ExecutionException: org.springframework.web.client.HttpServerErrorException: 500 null] с основной причиной

Мой код:

Контроллер:

@Autowired
public RestTemplate restTemplate;

@Autowired
public MyCallable myCallable;
@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;

    Iterable<Customer> customerIterable=repo.findAll();
    List<Customer> customers=new ArrayList<Customer>();
    customerIterable.forEach(customers::add);


    for(Customer c:customers) {

        myCallable.sendCustomerToInterface(c);
        //System.out.println(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";

}

MyCallable Класс:

public class MyCallable implements Callable<String>{

@Autowired
public RestTemplate restTemplate;

//int index=-1;

Customer c= c= new Customer();;
public void sendCustomerToInterface(Customer cust) {

    c= cust;
}

@Override
public String call() throws Exception {

    System.out.println("Customer no"+ c.getId() +"On thread Number"+Thread.currentThread().getId());
    return restTemplate.postForObject("http://localhost:3000/save", c, String.class);

}

}

Может ли кто-нибудь помочь мне с этим

Edit:

Full Stack Trace с ошибкой:

org.springframework.web.client.HttpServerErrorException: 500 null в org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:88) ~ [spring-web-4.3.13.RELEASE.jar: 4.3.13.RELEASE] в org.springframework.web.client.RestTemplate.handleResponse (RestTemplate.java:707) ~ [spring-web-4.3.13.RELEASE.jar: 4.3.13.RELEASE] в org.springframework.web.client.RestTemplate.doExecute (RestTemplate.java:660) ~ [spring-web-4.3.13.RELEASE.jar: 4.3.13.RELEASE] в org.springframework.web.client.RestTemplate.execute (RestTemplate.java:620) ~ [spring-web-4.3.13.RELEASE.jar: 4.3.13.RELEASE] в org.springframework.web.client.RestTemplate.postForObject (RestTemplate.java:387) ~ [spring-web-4.3.13.RELEASE.jar: 4.3.13.RELEASE] на com.OCADemoClient.OCADemoClient.MyCallable.call (MyCallable.java:32) ~ [classes /: na] на com.OCADemoClient.OCADemoClient.MyCallable.call (MyCallable.java:1) ~ [classes /: na] at java.util.concurrent.FutureTask.run (FutureTask.java:266) ~ [na: 1.8.0_181] в java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149) ~ [na: 1.8.0_181] в java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:624) ~ [na: 1.8.0_181] at java.lang.Thread.run (Thread.java:748) [na: 1.8.0_181]

1 Ответ

0 голосов
/ 24 января 2019

Согласно JavaDoc :

Исключение, выдаваемое при попытке получить результат задачи, которая была прервана с помощью исключения.

Проблема, похоже, в том, что для некоторых Customer звонок

    restTemplate.postForObject("http://localhost:3000/save", c, String.class);

приводит к ошибке сервера с кодом ответа HTTP "500"


Я заметил только после прочтения вашего комментария:

У вас есть только один MyCallable, общий для всех Customer с.

Это не сработает, потому что ваш MyCallable является объектом с состоянием (он хранит Customer с void sendCustomerToInterface(Customer cust) и должен получить этот конкретный Customer позже в методе call()).

Чтобы это работало, вы можете переписать MyCallable так:

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());
        return restTemplate.postForObject("http://localhost:3000/save", c, String.class);

    }
}

и в контроллере вы бы написали

for(Customer c:customers) {

    MyCallable myCallable = new MyCallable(restTemplate, c);
    //System.out.println(c);
    Future<String> future= executor.submit(myCallable);
    myFutureList.add(future);

}

Кстати, ваш код неэффективен. Вы можете пропустить создание списка customers и просто написать

for (Customer c: repo.findAll()) {
    //...
}
...