如何调用 REST API 并且不等待任何响应。

huangapple go评论75阅读模式
英文:

How to call rest api and do not wait any response

问题

我有这段代码

private Boolean doSomething() {
    // 一些代码
    this.sync();
    return true;
}

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

我不需要来自REST调用的数据。它是批处理执行服务,需要时间。但对于我的 doSomething 函数,我不需要从 sync 获取响应以继续。

今天,当REST调用不可用时...我的 doSomething 函数...什么都不做...

如何调用REST服务,但在没有错误的情况下继续执行 doSomething()

谢谢

我使用Java 11。

英文:

I have this code

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

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

I don't need data from the rest call. it's batch execution service he take times. but for my doSomething function i don't need a response from sync to continue.

Today, when the rest call not working, not available... my function doSomething .... do nothing...

How to call rest service but continue without error doSomething() without errors ??

Thanks

I use java 11

答案1

得分: 4

你可以将`sync`方法调用变成异步的Spring提供了简单的方法来实现这一点在你的任何配置类中即带有`@Configuration`注解的类添加`@EnableAsync`。如果你找不到任何配置类则在带有`@SpringBootApplication`注解的类中添加`@EnableAsync`。

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

然后在你的sync方法上添加@Async注解。你的代码将会是这样的。

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

为了让@Async起作用,需要从另一个类文件中调用这个sync方法。如果你从同一个类中调用sync,那么sync方法将不会是异步的。


<details>
<summary>英文:</summary>

You can make the `sync` method call asynchronous. Spring provides easy way to do that. Add `@EnableAsync` in any of you Configuration class (i.e. Classes annotated with `@Configuration`). If you don&#39;t find any configuration class then add `@EnableAsync` in the class with `@SpringBootApplication`.

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


Then add `@Async` to your `sync` method. Your code will look like this.

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

To make `@Async` work, this `sync` method need to be called from another class file. If you call `sync` from same class then sync method will not be asynchronous.

</details>



# 答案2
**得分**: 0

你不应该使用 RestTemplate 来调用 REST API。

"请考虑使用 org.springframework.web.reactive.client.WebClient,它具有更现代的API,并支持同步、异步和流式场景。"

链接:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

<details>
<summary>英文:</summary>

You should not use RestTemplate to call REST API.

&quot;Please, consider using the org.springframework.web.reactive.client.WebClient which has a more modern API and supports sync, async, and streaming scenarios.&quot;


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

</details>



# 答案3
**得分**: 0

如果您不希望从异步运行的方法中得到响应,那么您可以按照以下方式在触发端点中直接在`completableFuture`的lambda方法中执行异步部分,然后立即返回 200 OK。请注意,如果内部方法可能会抛出异常,您也需要在try/catch中捕获它,以确保它也以异步方式发生。

```java
@GetMapping(value = "/trigger")
public ResponseEntity<String> triggerMethod() throws Exception {

    CompletableFuture.runAsync(() -> {
        try {
            this.dosomething();
        } catch(Exception e) {
            e.printStackTrace();
        }
    });
    
    return new ResponseEntity<String>(HttpStatus.OK);
}

但是,如果您需要通过其他异步方法获得响应,则需要实现类似于这个示例中的方法。

英文:

If you dont want a response from the methods you run async, then You can simply do the async portion inside completableFuture lambda method as follows, directly in your triggering endpoint and return 200 ok immediately. Note, if internal method may throw exceptions, you need to swallow that too in a try/catch to ensure it happens asynch. as well.

<!-- language: java -->

@GetMapping(value = &quot;/trigger&quot;)
	public ResponseEntity&lt;String&gt; triggerMethod() throws Exception {
		

		  CompletableFuture.runAsync(() -&gt; {
			  try {
				
				this.dosomething();

			  } catch(Exception e) {e.printStackTrace();}

		  });
		  
		return new ResponseEntity&lt;String&gt;(HttpStatus.OK);
		
		
	}

However, if you require a response through other methods run asynchronously, then you will need to implement something like this example

答案4

得分: 0

你可以使用 Spring WebFlux 以反应式和非阻塞的方式构建或消费 API。以下是官方文档,详细解释了这一点:https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html。

英文:

You can use Spring WebFlux to build or consume API's in reactive and non-blocking manners.
Here is the official documentation which explains this in detail:
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html

huangapple
  • 本文由 发表于 2020年10月8日 16:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64258253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定