前言
Spring Boot 提供的restful服務(wù)這么方便,那有沒有方便的調(diào)用方式呢记餐?當(dāng)然有了那就是RestTemplate
一、什么是RestTemplate
傳統(tǒng)情況下在java代碼里訪問restful服務(wù),一般使用Apache的HttpClient尿孔。不過此種方法使用起來太過繁瑣待德。spring提供了一種簡單便捷的模板類來進行操作君丁,這就是RestTemplate。
二将宪、啟動服務(wù)
我們使用前一篇文章《架構(gòu)實戰(zhàn)篇(五):Spring Boot 表單驗證和異常處理》做服務(wù)端提供服務(wù)
啟動完畢后訪問
http://localhost:8081/swagger/swagger-ui.html
測試服務(wù)是否啟動正常
三绘闷、Java 客戶端
讓我們先來看下項目的目錄結(jié)構(gòu)
四、配置maven依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itunion</groupId>
<artifactId>spring-boot-resttemplate</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- 打war包用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<!-- 打war包用 -->
<finalName>swagger</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 打war包用,maven打包的時候告訴maven不需要web.xml,否剛會報找不到web.xml錯誤 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- -->
</plugins>
</build>
</project>
五较坛、編寫程序入口
程序的入口基本都一樣
package com.itunion;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws IOException {
SpringApplication.run(Application.class, args);
}
}
六印蔗、RestTemplate 配置
在這里我們可以設(shè)置連接的超時時間 代理 等信息
package com.itunion.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApiConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//單位為ms
factory.setConnectTimeout(5000);//單位為ms
return factory;
}
}
七、編寫API 返回對象
API 請求肯定少不了返回對象丑勤,為了方便類型轉(zhuǎn)換我們把User類復(fù)制了過來(實際開發(fā)中可以把api 公共的domain 等類帶jar 包出來)
package com.itunion.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用戶")
public class User {
@ApiModelProperty("編號")
private Long id;
@ApiModelProperty("用戶名")
private String username;
@ApiModelProperty("姓")
private String firstName;
@ApiModelProperty("名")
private String lastName;
@ApiModelProperty("郵箱")
private String email;
@ApiModelProperty(hidden = true)// 密碼不傳輸
@JsonIgnore
private String password;
@ApiModelProperty("狀態(tài)")
private Integer userStatus;
// get set
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", userStatus=" + userStatus +
'}';
}
}
異常類
package com.itunion.model;
import java.o.Serializable;
public class ErrorBody implements Serializable {
private Integer code;
private String message;
private long timestamp = System.currentTimeMillis();
// get set
@Override
public String toString() {
return "ErrorBody{" +
"code=" + code +
", message='" + message + '\'' +
", timestamp=" + timestamp +
'}';
}
}
八华嘹、使用RestTemplate 遠程調(diào)用
這里我們寫了兩個方法
- 當(dāng)遠程接口正常返回結(jié)果的時候我們會封裝成User對象返回到前端
- 當(dāng)遠程調(diào)用返回 RestClientResponseException 異常的時候封裝成ErrorBody對象(比如傳入?yún)?shù)不合法等數(shù)據(jù)驗證,不能返回逾期結(jié)果的時候會返回Error信息确封,這時候需要做處理)
package com.itunion.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itunion.model.ErrorBody;
import com.itunion.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
@Api(value = "用戶", description = "用戶")
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@ApiOperation(value = "調(diào)用遠程用戶服務(wù)", notes = "調(diào)用遠程用戶服務(wù)")
@RequestMapping(value = "/info/{userId}", method = RequestMethod.GET)
public User info(@PathVariable("userId") String userId) throws IOException {
String apiURL = "http://localhost:8081/swagger/user/info/" + userId;
return restTemplate.getForObject(apiURL, User.class);
}
@ExceptionHandler(RestClientResponseException.class)
public ErrorBody exceptionHandler(HttpClientErrorException e) throws IOException {
return new ObjectMapper().readValue(e.getResponseBodyAsString(), ErrorBody.class);
}
}
九除呵、修改端口
為了同時啟動兩個服務(wù)端口肯定是不能一樣的了
server.port=8082
server.context-path=/
swagger.enable=true
十、啟動程序和驗證
服務(wù)端成功啟動
客戶端成功啟動
訪問客戶端頁面
http://localhost:8082/swagger-ui.html
測試正確的請求參數(shù)
測試錯誤的請求參數(shù)
好了 RestTemplate 的簡單實用就到這里了
更多精彩內(nèi)容
架構(gòu)實戰(zhàn)篇(一):Spring Boot 整合MyBatis
架構(gòu)實戰(zhàn)篇(二):Spring Boot 整合Swagger2
架構(gòu)實戰(zhàn)篇(三):Spring Boot 整合MyBatis(二)
架構(gòu)實戰(zhàn)篇(四):Spring Boot 整合 Thymeleaf
架構(gòu)實戰(zhàn)篇(五):Spring Boot 表單驗證和異常處理
架構(gòu)實戰(zhàn)篇(六):Spring Boot RestTemplate的使用
關(guān)注我們
如果需要源碼可以關(guān)注“IT實戰(zhàn)聯(lián)盟”公眾號并留言(源碼名稱+郵箱)爪喘,小萌看到后會聯(lián)系作者發(fā)送到郵箱颜曾,也可以加入交流群和作者互撩哦~~~!