繁体   English   中英

使用 Rest 模板生成器调用方法

[英]calling method with Rest Template Builder

我使用 rest 模板生成器创建了这个 rest 模板,并设置了连接和读取超时。 我需要从程序中的其他方法调用此 rest 模板,但不确定如何调用。 请帮助,在此先感谢!

//create rest template with rest template builder and set connection and read timeouts        @Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {



    return restTemplateBuilder
            .setConnectTimeout(Duration.ofMillis(connectTimeout))
            .setReadTimeout(Duration.ofMillis(readTimeout))
            .build();
}

// this is an example method that calls rest template, unsure what goes in the parameter section
@Bean
public example example() {
    return new restTemplate(what goes here)
    );
}

RestTemplateBuilder是 Spring boot 提供的一个 bean。 您可以将其注入到任何 Spring bean 类中。

然后,您只想在创建 Spring bean class 时配置您的restTemplate并将其存储为一个字段。 您可以执行以下操作(这不是唯一的方法)。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

@Configuration
public class MyExampleRestClientConfiguration {
    private final RestTemplateBuilder restTemplateBuilder;

    @Autowired
    public MyExampleRestClient(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplateBuilder = restTemplateBuilder;
    }

    @Bean
    public RestTemplate restTemplate() {
        return restTemplateBuilder
        .setConnectTimeout(Duration.ofMillis(connectTimeout))
        .setReadTimeout(Duration.ofMillis(readTimeout))
        .build();
    }
}

现在在其他一些 spring bean class 中,您可以简单地连接restTemplate bean 并重新使用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class MyExampleRestClient {
  private final RestTemplate restTemplate;

  @Autowired
  public MyExampleRestClient(RestTemplate restTemplate) {
      this.restTemplate = restTemplate;
  }

  //Now You can call restTemplate in any method
}

你可以参考这个了解更多。

如果您已经创建了自定义的 RestTemplate,您可以将它自动连接到您想要调用它的任何 class 并使用它。 如果您有超过 1 个 RestTemplates,您可以在 RestTemplate Bean 上方使用 @Qualifier 并在调用 class 中使用相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM