springboot中使用RestTemplate调用rest服务

忘是亡心i 2022-01-28 01:31 673阅读 0赞

日常开发中,调用远程的rest服务是很常见的,比如微服务情况下的rest服务调用,又或者是调用第三方服务。微服务下的调用有服务注册与发现机制来调用,也可以使用RestTemplate方式来调用;而要是第三方服务,那么一般情况下是通过HTTP请求来调用。

接下来就看说一下在springboot项目中,用RestTemplate来调用远程rest服务,包括第三方服务。

首先我们的web项目中一般会有web依赖,此依赖中已有RestTemplate类,如下所示:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

其次假设有这样一个rest服务接口,提供一个简单的返回(服务的启动地址为“http://127.0.0.1:8080”),如下所示:

  1. @RestController
  2. @Slf4j
  3. public class RestServerController {
  4. @GetMapping("/rest/{name}")
  5. public String rest(@PathVariable String name) {
  6. log.info("request -> {}", name);
  7. return "Hello, " + name + " !";
  8. }
  9. }

那么我们要想调用这个服务,只需要用RestTemplate实例的方法即可成功调用。而RestTemplate默认是不会自动注入在spring容器中的,但是RestTemplateBuilder这个用来构建RestTemplate的实例是被注入的,所以需要用其来构建RestTemplate

配置一个构建RestTemplate的配置类如下:

  1. @Configuration
  2. public class RestTemplateConfig {
  3. @Resource
  4. private RestTemplateBuilder restTemplateBuilder;
  5. @Bean
  6. public RestTemplate buildRestTemplate() {
  7. return restTemplateBuilder
  8. .rootUri("http://127.0.0.1:8080")
  9. .setConnectTimeout(Duration.ofSeconds(5))
  10. .build();
  11. }
  12. }

最后在调用放做类似如下方式的调用即可:

  1. @Service
  2. public class RestTemplateService {
  3. private RestTemplate restTemplate;
  4. @Autowired
  5. public RestTemplateService(RestTemplate restTemplate) {
  6. this.restTemplate = restTemplate;
  7. }
  8. public void callRest() {
  9. String response = restTemplate.getForObject("/rest/{name}", String.class, "lazycece");
  10. System.out.println(response);
  11. }
  12. }

发表评论

表情:
评论列表 (有 0 条评论,673人围观)

还没有评论,来说两句吧...

相关阅读