这节课我们根据官网教程学习如何去消费(调用)一个 RESTful Web Service 。 原文链接 https://spring.io/guides/gs/consuming-rest/

本指南将引导您完成创建使用RESTful Web服务的应用程序的过程。

我们将会创建什么?

您将构建一个使用Spring RestTemplate的应用程序来检索http://gturnquist-quoters.cfapps.io/api/random中的随机Spring Boot引用。

你需要准备什么?

如何完成这个指南?

方法有很多种,这里我们仅通过STS来完成这个操作。

参考链接 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 中服务之间相互调用时最原生的其实是通过这种方式调用的。

源码:https://github.com/geekxingyun/JavaEE-Framework-Sample/tree/master/Spring-Consume-Restful-Web-Service-Sample

译:3.消费一个RESTful Web Service的更多相关文章

  1. 用Spring Tools Suite(STS)开始一个RESTful Web Service

    spring.io官方提供的例子Building a RESTful Web Service提供了用Maven.Gradle.STS构建一个RESTFul Web Service,实际上采用STS构建 ...

  2. 在GlassFish应用服务器上创建并运行你的第一个Restful Web Service【翻译】

    前言 本人一直开发Android应用,目前Android就业形势恶劣,甚至会一路下滑,因此决定学习服务器开发.采用的语言是java,IDE是Intellij,在下载Intellij的同时看到官网很多优 ...

  3. Spring Boot 构建一个 RESTful Web Service

    1  项目目标: 构建一个 web service,接收get 请求 http://localhost:8080/greeting 响应一个json 结果: {"id":1,&qu ...

  4. Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service

    实现目标 http://localhost:9000/rs/roomservice 为入口, http://localhost:9000/rs/roomservice/room为房间列表, http: ...

  5. JAX-RS 方式的 RESTful Web Service 开发

    JAX-RS 方式的 RESTful Web Service 开发 ——基于 CXF+Spring 的实现 Web Service 目前在风格上有两大类,一个是基于 SOAP 协议,一个是完全遵循 H ...

  6. 【转】Spring 4.x实现Restful web service

    http://my.oschina.net/yuyidi/blog/352909 首先我们还是跟之前一样,创建一个maven项目,不过因为Spring Restful web service是基于Sp ...

  7. 如何使用 JMeter 调用你的 Restful Web Service?进行简单的压力测试和自动化测试

    表述性状态传输(REST)作为对基于 SOAP 和 Web 服务描述语言(WSDL)的 Web 服务的简单替代,在 Web 开发上得到了广泛的接受.能够充分证明这点的是主流 Web 2.0 服务提供商 ...

  8. RESTful Web Service实战 小结1

    1 REST的基本实现形式HTTP+URI+XML,但不是唯一形式.XML后来被Json格式替代.REST是一中架构风格(Representational State Transfer,表述性状态转移 ...

  9. 构建一个基于 Spring 的 RESTful Web Service

    本文详细介绍了基于Spring创建一个“hello world” RESTful web service工程的步骤. 目标 构建一个service,接收如下HTTP GET请求: http://loc ...

随机推荐

  1. BZOJ1901 Zju2112 Dynamic Rankings 主席树

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ1901 题意概括 给你一段序列(n个数),让你支持一些操作(共m次), 有两种操作,一种是询问区间第 ...

  2. 全排列-hdu1027

    题目描述: 题目大意:现在给我们两个数字,N和M.我们应该编程找出由1到N组成的第M个最小序列.主要运用了全排列的思想,运用了全排列中next_permutation()函数: next_permut ...

  3. docker 部署springboot应用

    第一步:搭建springboot的web应用,可在CMD命令行中通过mvn install命令将应用打成jar包:如demo-0.0.1-SNAPSHOT.jar 第二步:将jar包copy到cent ...

  4. 006.ks.cfg文件相关

    一 图形化生成ks.cfg文件 [root@server ~]# yum -y install system-config-kickstart #安装图形化kickstart工具 [root@serv ...

  5. 上线---苹果AppStore审核注意事项,Guideline 1.2 - Safety - User Generated Content,2.1等条例(苹果审核六次拒绝)

    前段时间上线app,和战友一起撸了那么久的代码,上线是最激动的.然而安卓各大平台上线了半个月了,苹果却给了六次拒绝. 刚开始等苹果等的焦头烂额,现在内心毫无波澜,目前还在审核中...... 六次的拒绝 ...

  6. Android-LruCache与DiskLruCache

    Android LruCache与DiskLruCache 学习自 Android开发艺术探索 https://blog.csdn.net/guolin_blog/article/details/28 ...

  7. jquery.pagination.js添加跳转页

    原作者github地址:https://github.com/gbirke/jquery_pagination 在这基础上加入了跳转到指定页. 修改后的jquery.pagination.js /** ...

  8. 专业方向系列-00-Python与有限元初探

    案例1 给出4个弹簧的劲度系数,离散后,求其总的刚度矩阵. 代码: import numpy as np k1, k2, k3, k4 = 500, 250, 2000, 1000 ki = np.a ...

  9. Django-自定义增删改查组件的一些体会

    1.路由系统 namespace,用于区分相同name的url,通过namespace为url添加一个前缀 反向生成URL的时候 reverse('namespace:name') {% url &q ...

  10. Codeforces Round #532 (Div. 2)

    Codeforces Round #532 (Div. 2) A - Roman and Browser #include<bits/stdc++.h> #include<iostr ...