1.  配置AsyncRestTemplate

@Bean
public AsyncRestTemplate asyncRestTemplate() {
    return new AsyncRestTemplate();
}

 

2. 注入AsyncRestTemplate

@Autowired
private AsyncRestTemplate asyncRestTemplate;

 

3. 使用

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

String json = JSON.toJSONString(dto);
log.info("json数据:{}",json);


HttpEntity<String> entity = new HttpEntity(json,headers);

ListenableFuture<ResponseEntity<String>> response = asyncRestTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//回调函数
response.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
    //调用失败
    @Override
    public void onFailure(Throwable ex) {
        log.error("接口调用失败!",ex);
    }
    //调用成功
    @Override
    public void onSuccess(ResponseEntity<String> result) {

        log.info("返回数据:{}",result.getBody());

    }
});