如何调用rest api并且不等待任何响应

Flo*_*ian 1 java rest asynchronous spring-boot

我有这个代码

private Boolean doSomething() {
    // SOME CODE
    this.sync();
    return true;
}

public void sync() {
    RestTemplate restTemplate = restTemplate();
    restTemplate.exchange(batchHost, HttpMethod.GET, header(), String.class);
}
Run Code Online (Sandbox Code Playgroud)

我不需要其余通话中的数据。这是他需要时间的批量执行服务。但对于我的doSomething功能来说,我不需要回复即可sync继续。

今天,当其余的调用不起作用、不可用时...我的函数 doSomething .... 什么都不做...

如何调用休息服务但继续没有错误doSomething()没有错误?

谢谢

我用的是java 11

Sha*_*rup 5

您可以使sync方法调用异步。Spring 提供了简单的方法来做到这一点。添加@EnableAsync任何配置类(即用 注释的类@Configuration)。如果找不到任何配置类,请添加@EnableAsync带有@SpringBootApplication.

@SpringBootApplication
@EnableAsync
public class SpringbootApplication{
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后添加@Async到您的sync方法中。您的代码将如下所示。

@Async
public void sync() {
    RestTemplate restTemplate = restTemplate();
    restTemplate.exchange(batchHost, HttpMethod.GET, header(), String.class);
}
Run Code Online (Sandbox Code Playgroud)

为了使其@Async工作,sync需要从另一个类文件调用此方法。如果您sync从同一个类调用,则同步方法将不是异步的。