如何在Spring Boot 中在OAuth2RestTemplate中添加rest API请求超时?

gudnpqoy  于 2023-10-15  发布在  Spring
关注(0)|答案(1)|浏览(136)

在我的Sping Boot 微服务中,我使用OAuth2 RestTemplate进行rest API调用。现在,我们必须在rest API调用中添加请求超时,为此,我在www.example.com文件中尝试spring.mvc.mvc.request-timeout=20000application.properties,但没有工作。

@Configuration
public class ResourceConfig {

   @Bean
   @LoadBalanced
   @Qualifier("oauth2BalancedRestTemplate")
   public OAuth2RestTemplate oauth2BalancedRestTemplate(@Qualifier("oauth2RestTemplate") OAuth2RestTemplate bean) {
      OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(bean.getResource());
      restTemplate.setRequestFactory(bean.getRequestFactory());
      return restTemplate;
   }
   
   @Bean
   @LoadBalanced
   @Qualifier("oauth2JWTBalancedRestTemplate")
   public OAuth2RestTemplate oauth2JWTBalancedRestTemplate(@Qualifier("oauth2JWTRestTemplate") OAuth2RestTemplate bean) {
      OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(bean.getResource());
      restTemplate.setRequestFactory(bean.getRequestFactory());
      return restTemplate;
   } 
}

@Service
public class ApiCall {

   @Value("${url}")
   private String uri;
   
   @Value("${endpoint}")
   private String endpoint;
   
   @Autowired
   @Qualifier("oauth2JWTBalancedRestTemplate")
   private OAuth2RestTemplate restTemplate;

   public Response getTrdDetail(Request req) {
     HttpHeaders headers = new HttpHeaders();
     HttpEntity<Request> httpEntity = new HttpEntity<Request> (req, headers);
     return restTemplate.exchange(uri + endpoint, HttpMethod.POST, httpEntity, Response.class);
   
   }
}
7qhs6swi

7qhs6swi1#

确保这些依赖关系

<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>

配置HttpRequestFactory bean,然后将其注入到OAuth2RestTemplate bean中:

@Configuration
public class ResourceConfig {

    @Bean
    public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 5 seconds
        factory.setReadTimeout(5000);    // 5 seconds
        return factory;
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate() {
        ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
        resourceDetails.setAccessTokenUri("YOUR_ACCESS_TOKEN_URI");
        resourceDetails.setClientId("YOUR_CLIENT_ID");
        resourceDetails.setClientSecret("YOUR_CLIENT_SECRET");
        resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);

        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
        restTemplate.setRequestFactory(clientHttpRequestFactory());
        
        return restTemplate;
    }
}

相关问题