gpt4 book ai didi

spring - RestTemplate 设置每个请求的超时时间

转载 作者:行者123 更新时间:2023-12-04 12:14:04 30 4
gpt4 key购买 nike

我有一个 @Service有几种方法,每种方法使用不同的 web api。每个调用都应该有一个自定义的读取超时。
拥有一个 RestTemplate 实例并在每个方法中通过工厂更改超时是否是线程安全的

((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory())
.setReadTimeout(customMillis);

我担心的是我正在更改工厂的超时时间,它不像 RequestConfig .考虑到这些方法可能同时被多个用户调用,这种方法是否是线程安全的?或者每个方法都应该有自己的 RestTemplate ?

最佳答案

选项 1:多个 RestTemplate

如果要更改创建的连接的属性,则需要一个 RestTemplate每个配置。我最近遇到了同样的问题,并且有两个版本的 RestTemplate ,一个用于“短超时”,一个用于“长超时”。在每个组(短/长)中,我能够分享 RestTemplate .

让您的调用更改超时设置,创建连接,并希望最好的是等待发生的竞争条件。我会小心翼翼地创造不止一个 RestTemplate .

例子:

@Configuration
public class RestTemplateConfigs {
@Bean("shortTimeoutRestTemplate")
public RestTemplate shortTimeoutRestTemplate() {
// Create template with short timeout, see docs.
}
@Bean("longTimeoutRestTemplate")
public RestTemplate longTimeoutRestTemplate() {
// Create template with short timeout, see docs.
}
}

然后您可以根据需要将它们连接到您的服务中:
@Service
public class MyService {
private final RestTemplate shortTimeout;
private final RestTemplate longTimeout;

@Autowired
public MyService(@Qualifier("shortTimeoutRestTemplate") RestTemplate shortTimeout,
@Qualifier("longTimeoutRestTemplate") RestTemplate longTimeout) {
this.shortTimeout = shortTimeout;
this.longTimeout = longTimeout;
}

// Your business methods here...
}

选项 2:在断路器中包装调用

如果您正在调用外部服务,您可能是 should be using a circuit breaker为了这。 Spring Boot 与 Hystrix 配合得很好,Hystrix 是断路器模式的一种流行实现。使用 hystrix,您可以控制您调用的每个服务的回退和超时。

假设您对服务 A 有两种选择:1) 便宜但有时慢 2) 贵但速度快。您可以使用 Hystrix 来放弃廉价/慢速,而在真正需要时使用昂贵/快速。或者你可以没有备份,只让 Hystrix 调用一个提供合理默认值的方法。

未经测试的示例:
@EnableCircuitBreaker
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp .class, args);
}
}

@Service
public class MyService {
private final RestTemplate restTemplate;

public BookService(RestTemplate rest) {
this.restTemplate = rest;
}

@HystrixCommand(
fallbackMethod = "fooMethodFallback",
commandProperties = {
@HystrixProperty(
name = "execution.isolation.thread.timeoutInMilliseconds",
value="5000"
)
}
)
public String fooMethod() {
// Your logic here.
restTemplate.exchange(...);
}

public String fooMethodFallback(Throwable t) {
log.error("Fallback happened", t);
return "Sensible Default Here!"
}
}

回退方法也有选项。您可以使用 @HystrixCommand 注释该方法并尝试另一个服务调用。或者,您可以只提供一个合理的默认值。

关于spring - RestTemplate 设置每个请求的超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361794/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com