首页 > 解决方案 > 线程如何在 Spring Async 函数中成功终止以及如何在 java 中的多线程方法中递归调用相同的函数

问题描述

我正在@Async从我的控制器调用函数,看起来线程在完成类中的makeCallWithRestTemplate方法后没有终止HttpServiceClient

请求结构

[ 
    { independent task 1
    },
    { dependent task 1,
        "dependency": { // dependency is that, execute task 1 first 
                        and then based on its result code execute dependent task 1
            "===": [
            "$[0].response.http_body.action.result_code",
            "SUCCESS"
            ]
        }
    }
]

控制器

@RestController
@RequestMapping("/abc")
public class ActionController {
    @Autowired
    private HttpServiceClient client;
    @PostMapping
    public ResponseEntity<JsonNode> performMultipleActions(@RequestBody List<List<ABC>> abc) {
            return client.callExternalService(abc);
    }
}

@Component
public class HttpServiceClient {
    @Autowired
    private RestTemplate restTemplate; 
    @Async
    public CompletableFuture<Map<Integer, ResponseEntity<JsonNode>>> makeCallWithRestTemplate(
            List<ABC> requests) throws IOException { 
        int index = -1;
        Map map = new hashmap();
    while (iterator.hasNext()) { 
        index++;
        Abc abc = iterator.next();
        if (dependency == null) {
           extracted(mapOfResult, index, action);
        }else{
        //create a map of with index as a key and object as a value
        map.put(index, request); 
        }
        // **Question 3-** once all the independent task will get executed wait here, Now my question is how to wait here ? 
        //**Question 4-** once wait complete again call restTemplate.exchange method with dependent task, how can i make it recursive, will my hashmap would be threadsafe in recursive?
    }
    return CompletableFuture.completedFuture(exchange);
    }
}
private void extracted(Map<Integer, ResponseEntity<JsonNode>> mapOfResult, int index, ActionRequest action)
            throws JsonProcessingException, JsonMappingException {
 ResponseEntity<JsonNode> exchange = restTemplate.exchange(urlObj,
                            HttpMethod.resolve(action.getMethod()), entity, JsonNode.class); 
    mapOfResult.put(index, exchange);
}

标签: javamultithreadingspring-bootasynchronouscompletable-future

解决方案


推荐阅读