SpringBoot 使用RestTemplate实现调用服务

SpringBoot的搭建可以看一下我之前写的一篇博客

https://blog.csdn.net/cwr452829537/article/details/81351987

准备工作

要使用RestTemplate需要引入依赖,web依赖也可以在创建项目时选择Web -> Web

<!-- web -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>


<!-- 远程调用 httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

 注入RestTemplate

  首先需要在Application中加入一个RestTemplate


  
  
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
  5. import org.springframework.web.client.RestTemplate;
  6. @SpringBootApplication
  7. public class RemoteApplication {
  8. @Bean //必须new 一个RestTemplate并放入spring容器当中,否则启动时报错
  9. public RestTemplate restTemplate() {
  10. HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  11. httpRequestFactory.setConnectionRequestTimeout( 30 * 1000);
  12. httpRequestFactory.setConnectTimeout( 30 * 3000);
  13. httpRequestFactory.setReadTimeout( 30 * 3000);
  14. return new RestTemplate(httpRequestFactory);
  15. }
  16. public static void main(String[] args) {
  17. SpringApplication.run(RemoteApplication.class, args);
  18. }
  19. }

 调用服务

  实体类


  
  
  1. import com.fasterxml.jackson.annotation.JsonProperty;
  2. import lombok.Data;
  3. @Data
  4. public class UserEntity {
  5. @JsonProperty( "user_id")
  6. private Long userId;
  7. private String name;
  8. private String phone;
  9. }

  
  
  1. import lombok.Data;
  2. @Data
  3. public class Result {
  4. private Integer code;
  5. private String message;
  6. }

  controller


  
  
  1. import com.cwr.remote.model.db.UserEntity;
  2. import com.cwr.remote.model.vo.Result;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.*;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.client.RestTemplate;
  7. @RequestMapping( "/remote")
  8. //允许跨域访问
  9. @CrossOrigin(origins = "*", maxAge = 3600)
  10. @RestController
  11. public class RemoteController {
  12. //自动注入RestTemplate
  13. private final RestTemplate restTemplate;
  14. @Autowired
  15. public RemoteController(RestTemplate restTemplate) {
  16. this.restTemplate = restTemplate;
  17. }
  18. /**
  19. * 调用远程服务添加用户信息
  20. *
  21. * @param userEntity 用户实体
  22. * @return
  23. */
  24. @PostMapping( "/add-user")
  25. public Result addUser(@RequestBody UserEntity userEntity) {
  26. HttpEntity<UserEntity> entity = new HttpEntity<>(userEntity);
  27. ResponseEntity<Result> resultResponseEntity = this.restTemplate.exchange(
  28. "http://xxx.xxx.xxx.xxx/user/add",
  29. HttpMethod.POST, entity, Result.class);
  30. if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
  31. return resultResponseEntity.getBody();
  32. }
  33. return null;
  34. }
  35. /**
  36. * 调用远程服务查询单个用户信息
  37. *
  38. * @param id 用户id
  39. * @return
  40. */
  41. @GetMapping( "/find-user-id/{id}")
  42. public UserEntity findOne(@PathVariable Long id) {
  43. ResponseEntity<UserEntity> resultResponseEntity = this.restTemplate.exchange(
  44. String.format( "http://xxx.xxx.xxx.xxx/user/find-id/%s", id),
  45. HttpMethod.GET, null, UserEntity.class);
  46. if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
  47. return resultResponseEntity.getBody();
  48. }
  49. return null;
  50. }
  51. }

这里详细讲一下exchange( )方法

public <T> ResponseEntity<T>

           exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType) 

  •     url:请求地址,如果需要在url中带参数,使用String.format(),用%s拼接即可;
  •     method:请求方式,HttpMethod是一个枚举类型,有GET、POST、DELETE等方法;
  •     requestEntity:请求参数,这个主要是POST等有请求体的方法才需要,GET、DELETE等方法可以为null;
  •     responseType:返回数据类型。

测试结果(我使用的是Postman)

   

发布了244 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44813090/article/details/105342862