这节课咱们根据官网教程学习如何去消费(调用)一个 RESTful Web Service 。 原文连接 https://spring.io/guides/gs/consuming-rest/java
本指南将引导您完成建立使用RESTful Web服务的应用程序的过程。git
您将构建一个使用Spring RestTemplate的应用程序来检索http://gturnquist-quoters.cfapps.io/api/random中的随机Spring Boot引用。github
JDK1.8 或者更高web
Gradle 4+ 或者 Maven 3.2+spring
你也能够直接导入Code 到你的IDE中apache
方法有不少种,这里咱们仅经过STS来完成这个操做。api
参考连接 https://spring.io/guides/gs/sts/浏览器
1. 打开咱们的STS,点击左上角的File————> New ————> Import Spring Getting Started Content
2. 咱们这里输入 rest 来搜索出“Consuming Rest”
Tips:这里勾选构建的类型是Maven项目,Code Sets 两个都勾选,这样会生成两个Project.
complete 是表示已经写好的code,initial是初始化空的项目,咱们待会就在这个空的项目中进行修改和尝试。
3. 经过完成项目设置,您能够建立一个使用RESTful服务的简单应用程序。
一个RESTful服务已经在http://gturnquist-quoters.cfapps.io/api/random 站起来了。 它随机提取有关Spring Boot的引用,并将它们做为JSON文档返回。
若是您经过网络浏览器或curl请求该URL,您将收到一个以下所示的JSON文档:
{"type":"success","value":{"id":2,"quote":"With Boot you deploy everywhere you can find a JVM basically."}}
很简单,但经过浏览器获取时不会很是有用。以编程方式更有用的方式来使用REST Web服务。
为了帮助你完成这个任务,Spring提供了一个名为RestTemplate的方便的模板类。 RestTemplate使大多数RESTful服务与单行咒语交互。 它甚至能够将该数据绑定到自定义域类型。
4. 首先咱们须要建立一个Domain 实体类
package hello; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Quote { private String type; private Value value; public Quote() { } public String getType() { return type; } public void setType(String type) { this.type = type; } public Value getValue() { return value; } public void setValue(Value value) { this.value = value; } @Override public String toString() { return "Quote{" + "type='" + type + '\'' + ", value=" + value + '}'; } }
正如你所看到的,这是一个简单的Java类,它有一些属性和匹配的getter方法。 它使用Jackson JSON处理库中的@JsonIgnoreProperties进行了注释,以指示任何未绑定在此类型的属性都应该被忽略。
为了直接将数据绑定到自定义类型,您须要指定变量的名称与从API返回的JSON文档中的键彻底相同。 若是JSON文档中的变量名和键不匹配,则须要使用@JsonProperty 注解来指定JSON文档的确切键。
Tips: 注意上面返回的JSON中字段名称是type和value 因此这里咱们定义的也是type和value.
5. 须要额外的类来嵌入内部报价自己。
package hello; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Value { private Long id; private String quote; public Value() { } public Long getId() { return this.id; } public String getQuote() { return this.quote; } public void setId(Long id) { this.id = id; } public void setQuote(String quote) { this.quote = quote; } @Override public String toString() { return "Value{" + "id=" + id + ", quote='" + quote + '\'' + '}'; } }
Tips: 因为上面返回的JSON 中value 是一个对象,包含id和quote,因此这里咱们须要一个额外的类来定义它。
6.使这个应用程序变得可执行
虽然能够将此服务做为传统WAR文件打包以部署到外部应用程序服务器,但下面演示的更简单的方法会建立独立应用程序。 您将全部内容打包到一个单独的,可执行的JAR文件中,由一个良好的旧Java main()方法驱动。 一路上,您使用Spring的支持将Tomcat servlet容器做为HTTP运行时嵌入,而不是部署到外部实例。
如今您能够编写使用RestTemplate的Application类来从Spring Boot报价服务中获取数据。
package hello; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { // TODO Auto-generated method stub RestTemplate restTemplate = new RestTemplate(); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); } }
Tips: 这里咱们能够看到经过一个RestTemplate 对象的方法,咱们消费(调用)了另一个Restfule web service 的数据。有了这种调用方式,咱们便将再也不须要编写Httpclient方法来处理调用。
因为Jackson JSON处理库位于类路径中,RestTemplate将使用它(经过消息转换器)将传入的JSON数据转换为Quote对象。 从那里,Quote对象的内容将被记录到控制台。
在这里,您只使用RestTemplate进行HTTP GET请求。 但RestTemplate还支持其余HTTP动词,例如POST,PUT和DELETE。
打印控制台如图所示:
7. 使用Spring Boot管理应用程序生命周期
到目前为止,咱们尚未在咱们的应用程序中使用过Spring Boot,但这样作有一些优势,并且这并不难。 其中一个优势是咱们可能但愿让Spring Boot管理RestTemplate中的消息转换器,以便自定义很容易以声明方式添加。 为此,咱们在主类上使用@SpringBootApplication并转换主要方法来启动它,就像在任何Spring Boot应用程序中同样。 最后,咱们将RestTemplate移动到一个CommandLineRunner回调函数中,以便在启动时由Spring Boot执行:
src/main/java/hello/Application.java
package hello; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { // TODO Auto-generated method stub SpringApplication.run(Application.class); // RestTemplate restTemplate = new RestTemplate(); // Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); // log.info(quote.toString()); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }; } }
Tips: 刚才那种方式显然并不优雅,咱们注释掉刚才的内容更换成使用Spring Boot 的code 来看下。经过这种方式显然更优雅地调用了 其余Restful Web service.
RestTemplateBuilder由Spring注入,若是您使用它建立RestTemplate,那么您将受益于Spring Boot中使用消息转换器和请求工厂进行的全部自动配置。
咱们还将RestTemplate提取到@Bean中以使其更易于测试(这样能够更轻松地进行模拟)。
8.编译生一个可执行的Jar
您可使用Gradle或Maven从命令行运行应用程序。 或者您能够构建一个包含全部必需的依赖项,类和资源的可执行JAR文件,并运行该文件。 这使得在整个开发生命周期内跨越不一样环境等,将服务做为应用程序发布,版本化和部署变得很是容易。
这一步咱们使用STS中集成的工具来操做生成一个可执行的Jar,如图所示:
以后咱们应该能看到target 文件夹下多了一个文件
若是您正在使用Gradle,则可使用./gradlew bootRun运行该应用程序。 或者您可使用./gradlew构建构建JAR文件。 而后你能够运行JAR文件:
java -jar build/libs/gs-consuming-rest-0.1.0.jar
若是您使用的是Maven,则可使用./mvnw spring-boot:run来运行该应用程序。 或者,您可使用./mvnw clean包构建JAR文件。 而后你能够运行JAR文件:
java -jar target/gs-consuming-rest-0.1.0.jar
上述过程将建立一个可运行的JAR。 您也能够选择构建经典的WAR文件。
您应该看到以下所示的输出,并随机引用:
若是你看到错误没法提取响应:没有找到合适的HttpMessageConverter用于响应类型[class hello.Quote],那么你有可能处于一个没法链接到后端服务的环境中(若是能够的话,它会发送JSON)。 也许你背后是一个公司代理? 尝试将标准系统属性http.proxyHost和http.proxyPort设置为适合您的环境的值。
好了本节课到这里就结束了,经过本节课咱们发现Spring Boot 中服务之间相互调用时最原生的实际上是经过这种方式调用的。