天天看點

SpringBoot 使用RestTemplate實作調用服務準備工作 注入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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RemoteApplication {
    @Bean //必須new 一個RestTemplate并放入spring容器當中,否則啟動時報錯
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30 * 1000);
        httpRequestFactory.setConnectTimeout(30 * 3000);
        httpRequestFactory.setReadTimeout(30 * 3000);
        return new RestTemplate(httpRequestFactory);
    }
    public static void main(String[] args) {
        SpringApplication.run(RemoteApplication.class, args);
    }
}
           

 調用服務

  實體類

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class UserEntity {
    @JsonProperty("user_id")
    private Long userId;
    private String name;
    private String phone;
}
           
import lombok.Data;

@Data
public class Result {
    private Integer code;
    private String message;
}
           

  controller

import com.cwr.remote.model.db.UserEntity;
import com.cwr.remote.model.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RequestMapping("/remote")
//允許跨域通路
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class RemoteController {
    //自動注入RestTemplate 
    private final RestTemplate restTemplate;

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

    /**
     * 調用遠端服務添加使用者資訊
     *
     * @param userEntity 使用者實體
     * @return
     */
    @PostMapping("/add-user")
    public Result addUser(@RequestBody UserEntity userEntity) {
        HttpEntity<UserEntity> entity = new HttpEntity<>(userEntity);
        ResponseEntity<Result> resultResponseEntity = this.restTemplate.exchange(
                "http://xxx.xxx.xxx.xxx/user/add",
                HttpMethod.POST, entity, Result.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }

    /**
     * 調用遠端服務查詢單個使用者資訊
     *
     * @param id 使用者id
     * @return
     */
    @GetMapping("/find-user-id/{id}")
    public UserEntity findOne(@PathVariable Long id) {
        ResponseEntity<UserEntity> resultResponseEntity = this.restTemplate.exchange(
                String.format("http://xxx.xxx.xxx.xxx/user/find-id/%s", id),
                HttpMethod.GET, null, UserEntity.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }
}
           

這裡詳細講一下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)

SpringBoot 使用RestTemplate實作調用服務準備工作 注入RestTemplate 調用服務
SpringBoot 使用RestTemplate實作調用服務準備工作 注入RestTemplate 調用服務