1. 程式人生 > 實用技巧 >SpringCloud(3) ------>RestTemplate呼叫介面示例

SpringCloud(3) ------>RestTemplate呼叫介面示例

RestTemplate是一個HTTP客戶端,使用它我們可以方便的呼叫HTTP介面,支援GETPOSTPUTDELETE等方法。

一、gRestTempetForObject方法

1、通過RestTemplate傳送Get請求

 wordAppUrl為服務名字

 @GetMapping("/findAllWord")
    public CommonResult findAllWord(@RequestParam String userCode) {
        return restTemplate.getForObject(wordAppUrl + "/word/findWordByUserCode?userCode={1}", CommonResult.class
, userCode); }
 @GetMapping("/findWordById2")
    public CommonResult findWordById2(@RequestParam Integer id) {
        return restTemplate.getForObject(wordAppUrl + "/word/findById2?id={1}", CommonResult.class, id);
    }

2、通過RestTemplate傳送Post請求

  /**
     * 根據Id集合查詢
     * postForObject 測試
     
*/ @GetMapping("/findWordByIds") public CommonResult findWordByIds() { Integer[] ids = {1,2,3}; return restTemplate.postForObject(wordAppUrl + "/word/findByIds",ids, CommonResult.class); }
   /**
     * postForObject 測試
     */
    @GetMapping("/createWord")
    public CommonResult createWord() {
        Word word 
= Word.builder().id(101).chinese("自己").english("self").author("liangd").commitTime(new Date()).build(); return restTemplate.postForObject(wordAppUrl + "/word/create", JSONObject.toJSON(word), CommonResult.class); }

3、通過RestTemplate傳送Put請求

    /**
     * put 測試
     */
    @GetMapping("/updateWord")
    public CommonResult updateWord() {
        Word word = Word.builder().id(101).chinese("愛好").english("hobby").author("liangd").commitTime(new Date()).build();
        restTemplate.put(wordAppUrl + "/word/update", JSONObject.toJSON(word),CommonResult.class);
        return CommonResult.success(null);
    }

4、通過RestTemplate傳送Delete請求

  /**
     * delete 測試
     */
    @GetMapping("/deleteWord")
    public CommonResult deleteWord() {
        Integer id = 101;
        restTemplate.delete(wordAppUrl + "/word/delete?id={1}", id);
        return CommonResult.success(null);
    }

二、getForEntity方法

  返回物件為ResponseEntity物件,包含了響應中的一些重要資訊,比如響應頭、響應狀態碼、響應體等,

@GetMapping("/findWordById1/{id}")
    public CommonResult findWordById1(@PathVariable Integer id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(wordAppUrl + "/word/findById1/{1}", CommonResult.class, id);
        System.out.println(forEntity);
        return forEntity.getBody();
    }

三、配置RestTemplate

@Configuration
public class RibbonConfig {
    /**
     * /使用@LoadBalanced註解賦予RestTemplate負載均衡的能力
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

四、pom檔案新增ribbon依賴

  <!--負載均衡ribbon-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>