关于spring:Spring认证指南了解如何使用-Spring-Boot-Actuator-创建-RESTful-Web-服务

4次阅读

共计 8141 个字符,预计需要花费 21 分钟才能阅读完成。

原题目:Spring 认证指南 - 理解如何应用 Spring Boot Actuator 创立 RESTful Web 服务。(起源:Spring 中国教育管理中心)

Spring 认证指南:如何应用 Spring Boot Actuator 创立 RESTful Web 服务
应用 Spring Boot Actuator 构建 RESTful Web 服务
Spring Boot Actuator 是 Spring Boot 的一个子项目。它为您的应用程序增加了几项生产级服务,您无需付出任何致力。在本指南中,您将构建一个应用程序,而后理解如何增加这些服务。

你将建造什么
本指南将疏导您应用 Spring Boot Actuator 创立“Hello, world”RESTful Web 服务。您将构建一个承受以下 HTTP GET 申请的服务:

$ curl http://localhost:9000/hello-w…

它应用以下 JSON 响应:

{“id”:1,”content”:”Hello, World!”}

您的应用程序中还增加了许多性能,用于在生产(或其余)环境中治理服务。您构建的服务的业务性能与构建 RESTful Web 服务中的雷同。您无需应用该指南即可利用此指南,只管比拟后果可能会很乏味。

你须要什么
约 15 分钟
最喜爱的文本编辑器或 IDE
JDK 1.8 或更高版本
Gradle 4+ 或 Maven 3.2+
您还能够将代码间接导入 IDE:
弹簧工具套件 (STS)
IntelliJ IDEA
如何实现本指南
像大多数 Spring 入门指南一样,您能够从头开始并实现每个步骤,也能够绕过您曾经相熟的根本设置步骤。无论哪种形式,您最终都会失去工作代码。

要从头开始,请持续从 Spring Initializr 开始。

要跳过基础知识,请执行以下操作:

下载并解压本指南的源代码库,或应用 Git 克隆它:git clone https://github.com/spring-gui…
光盘进入 gs-actuator-service/initial
持续创立一个示意类。
实现后,您能够对照中的代码查看后果
gs-actuator-service/complete。

从 Spring Initializr 开始
您能够应用这个事后初始化的我的项目并单击 Generate 下载 ZIP 文件。此我的项目配置为适宜本教程中的示例。

手动初始化我的项目:

导航到 https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您实现大部分设置。
抉择 Gradle 或 Maven 以及您要应用的语言。本指南假设您抉择了 Java。
单击 Dependencies 并抉择 Spring Web 和 Spring Boot Actuator。
单击生成。
下载生成的 ZIP 文件,该文件是依据您的抉择配置的 Web 应用程序的存档。
如果您的 IDE 具备 Spring Initializr 集成,您能够从您的 IDE 实现此过程。

你也能够从 Github 上 fork 我的项目并在你的 IDE 或其余编辑器中关上它。

运行空服务
Spring Initializr 创立了一个空应用程序,您能够应用它来开始。以下示例(来自目录
src/main/java/com/example/actuatorservice/ActuatorServiceApplication 中 initial)显示了 Spring Initializr 创立的类:

package com.example.actuatorservice;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class ActuatorServiceApplication {

public static void main(String[] args) {

SpringApplication.run(ActuatorServiceApplication.class, args);

}

}

正文提供了一系列默认值(如 @SpringBootApplication 嵌入式 servlet 容器),具体取决于类门路的内容和其余内容。它还关上了 Spring MVC 的 @EnableWebMvc 注解,它激活了 Web 端点。

此应用程序中没有定义端点,但足以启动事物并查看 Actuator 的一些性能。该 SpringApplication.run()命令晓得如何启动 Web 应用程序。您须要做的就是运行以下命令:

$ ./gradlew clean build && java -jar build/libs/gs-actuator-service-0.1.0.jar

您还没有编写任何代码,那么产生了什么?要查看答案,请期待服务器启动,关上另一个终端,而后尝试以下命令(显示其输入):

$ curl localhost:8080

{“timestamp”:1384788106983,”error”:”Not Found”,”status”:404,”message”:””}

上述命令的输入表明服务器正在运行,但您尚未定义任何业务端点。/error 您会看到来自 Actuator 端点的通用 JSON 响应,而不是默认的容器生成的 HTML 谬误响应。您能够在服务器启动的控制台日志中看到开箱即用的端点。您能够尝试其中一些端点,包含 /health 端点。以下示例显示了如何执行此操作:

$ curl localhost:8080/actuator/health

{“status”:”UP”}

状态为 UP,因而执行器服务正在运行。

无关详细信息,请参阅 Spring Boot 的执行器我的项目。

创立一个示意类
首先,您须要考虑一下您的 API 会是什么样子。

您想解决 GET 申请 /hello-world,能够抉择应用名称查问参数。为了响应这样的申请,您想要发回 JSON,示意问候语,如下所示:

{

“id”: 1,

“content”: “Hello, World!”

}

该 id 字段是问候语的惟一标识符,并 content 蕴含问候语的文本示意。

要对问候示意进行建模,请创立一个示意类。以下清单(来自
src/main/java/com/example/actuatorservice/Greeting.java)显示了 Greeting 该类:

package com.example.actuatorservice;

public class Greeting {

private final long id;

private final String content;

public Greeting(long id, String content) {

this.id = id;

this.content = content;

}

public long getId() {

return id;

}

public String getContent() {

return content;

}

}

当初您须要创立将服务于示意类的端点控制器。

创立资源控制器
在 Spring 中,REST 端点是 Spring MVC 控制器。以下 Spring MVC 控制器(来自
src/main/java/com/example/actuatorservice/HelloWorldController.java)解决 /hello-world 端点的 GET 申请并返回 Greeting 资源:

package com.example.actuatorservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

public class HelloWorldController {

private static final String template = “Hello, %s!”;

private final AtomicLong counter = new AtomicLong();

@GetMapping(“/hello-world”)

@ResponseBody

public Greeting sayHello(@RequestParam(name=”name”, required=false, defaultValue=”Stranger”) String name) {

return new Greeting(counter.incrementAndGet(), String.format(template, name));

}

}

面向人类的控制器和 REST 端点控制器之间的次要区别在于如何创立响应。端点控制器不依赖视图(例如 JSP)以 HTML 格局出现模型数据,而是将要写入的数据间接返回到响应的注释中。

注解通知 Spring MVC 不要将 @ResponseBody 模型渲染到视图中,而是将返回的对象写入响应注释中。它通过应用 Spring 的音讯转换器之一来实现。因为 Jackson 2 在类门路中,如果申请的标头指定应返回 JSON,
MappingJackson2HttpMessageConverter 则将解决对象到 JSON 的转换。GreetingAccept

你怎么晓得 Jackson 2 在类门路上?运行 mvn dependency:tree 或./gradlew dependencies,您将取得蕴含 Jackson 2.x 的具体依赖树。您还能够看到它来自 /spring-boot-starter-json,它自身由 spring-boot-starter-web 导入。

运行应用程序
您能够从自定义主类或间接从配置类之一运行应用程序。对于这个简略的示例,您能够应用 SpringApplication 帮忙程序类。请留神,这是 Spring Initializr 为您创立的应用程序类,您甚至无需对其进行批改即可使其实用于这个简略的应用程序。以下清单(来自
src/main/java/com/example/actuatorservice/HelloWorldApplication.java)显示了应用程序类:

package com.example.actuatorservice;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class HelloWorldApplication {

public static void main(String[] args) {

SpringApplication.run(HelloWorldApplication.class, args);

}

}

在传统的 Spring MVC 应用程序中,您将增加 @EnableWebMvc 以关上要害行为,包含配置 DispatcherServlet. 然而当 Spring Boot 在你的类门路上检测到 spring-webmvc 时,它会主动关上这个注解。这使您能够在接下来的步骤中构建控制器。

@SpringBootApplication 正文还引入了一个正文 @ComponentScan,它通知 Spring 扫描
com.example.actuatorservice 包中的那些控制器(以及任何其余带正文的组件类)。

构建一个可执行的 JAR
您能够应用 Gradle 或 Maven 从命令行运行应用程序。您还能够构建一个蕴含所有必要依赖项、类和资源的单个可执行 JAR 文件并运行它。构建可执行 jar 能够在整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。

如果您应用 Gradle,则能够应用./gradlew bootRun. 或者,您能够应用构建 JAR 文件./gradlew build,而后运行 ​JAR 文件,如下所示:

java -jar build/libs/gs-actuator-service-0.1.0.jar
如果您应用 Maven,则能够应用./mvnw spring-boot:run. 或者,您能够应用构建 JAR 文件,./mvnw clean package 而后运行该 JAR 文件,如下所示:

java -jar 指标 /gs-actuator-service-0.1.0.jar
此处形容的步骤创立了一个可运行的 JAR。您还能够构建经典的 WAR 文件。

一旦服务运行(因为您 spring-boot:run 在终端中运行),您能够通过在独自的终端中运行以下命令来测试它:

$ curl localhost:8080/hello-world

{“id”:1,”content”:”Hello, Stranger!”}

切换到不同的服务器端口
Spring Boot Actuator 默认在端口 8080 上运行。通过增加 application.properties 文件,您能够笼罩该设置。以下清单(来自
src/main/resources/application.properties)显示了具备必要更改的文件:

server.port: 9000

management.server.port: 9001

management.server.address: 127.0.0.1

通过在终端中运行以下命令再次运行服务器:

$ ./gradlew clean build && java -jar build/libs/gs-actuator-service-0.1.0.jar
该服务当初在端口 9000 上启动。

您能够通过在终端中运行以下命令来测试它是否在端口 9000 上工作:

$ curl localhost:8080/hello-world

curl: (52) Empty reply from server

$ curl localhost:9000/hello-world

{“id”:1,”content”:”Hello, Stranger!”}

$ curl localhost:9001/actuator/health

{“status”:”UP”}

测试您的应用程序
要查看您的应用程序是否工作,您应该为您的应用程序编写单元和集成测试。中的测试类
src/test/java/com/example/actuatorservice/HelloWorldApplicationTests.java 确保

您的控制器有响应。
您的治理端点是响应式的。
请留神,测试会在随机端口上启动应用程序。以下清单显示了测试类:

/*

  • Copyright 2012-2014 the original author or authors.

*

  • Licensed under the Apache License, Version 2.0 (the “License”);
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at

*

  • https://www.apache.org/licens…

*

  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an “AS IS” BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/

package com.example.actuatorservice;

import java.util.Map;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.boot.test.web.client.TestRestTemplate;

import org.springframework.boot.web.server.LocalServerPort;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.test.context.TestPropertySource;

import static org.assertj.core.api.BDDAssertions.then;

/**

  • Basic integration tests for service demo application.

*

  • @author Dave Syer

*/

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

@TestPropertySource(properties = {“management.port=0”})

public class HelloWorldApplicationTests {

@LocalServerPort

private int port;

@Value(“${local.management.port}”)

private int mgt;

@Autowired

private TestRestTemplate testRestTemplate;

@Test

public void shouldReturn200WhenSendingRequestToController() throws Exception {

@SuppressWarnings(“rawtypes”)

ResponseEntity<Map> entity = this.testRestTemplate.getForEntity(

“http://localhost:” + this.port + “/hello-world”, Map.class);

then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

}

@Test

public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Exception {

@SuppressWarnings(“rawtypes”)

ResponseEntity<Map> entity = this.testRestTemplate.getForEntity(

“http://localhost:” + this.mgt + “/actuator”, Map.class);

then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

}

}

概括
祝贺!您刚刚应用 Spring 开发了一个简略的 RESTful 服务,并应用 Spring Boot Actuator 增加了一些有用的内置服务。

正文完
 0