013 使用SpringBootActuator 构建Restful web服务

原文

https://spring.io/guides/gs/actuator-service/

直译

运行空服务

对于初学者来说,这是一个空的Spring MVC应用程序。

src/main/java/hello/HelloWorldApplication.java

package hello;

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);
    }

}

该@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”:“”}

所以服务器正在运行,但您还没有定义任何业务端点。您可以从Actuator /error端点看到一个通用的JSON响应,而不是默认的容器生成的HTML错误响应。您可以在服务器启动的控制台日志中看到开箱即用的端点。例如,尝试一些

$ 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/hello/Greeting.java

package hello;

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控制器处理/ hello-world的GET请求并返回Greeting资源:

src/main/java/hello/HelloWorldController.java

package hello;

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中的模型数据,而是简单地将要写入的数据直接返回到响应的主体。

该@ResponseBody注解告诉Spring MVC不是渲染模型到视图,而是写在返回的对象在响应主体。它通过使用Spring的消息转换器之一来实现。因为Jackson 2在类路径中,这意味着MappingJackson2HttpMessageConverter如果请求的Accept标头指定应该返回JSON ,它将处理Greeting转换为JSON 。

你怎么知道Jackson 2在课堂上?运行mvn dependency:tree或者./gradlew dependencies你将得到一个详细的依赖关系树,它显示了Jackson 2.x. 您还可以看到它来自/ spring-boot-starter-json,它本身是由spring-boot-starter-web导入的。
创建可执行的主类
您可以从自定义主类启动应用程序,或者我们可以直接从其中一个配置类执行此操作。最简单的方法是使用SpringApplication辅助类:

src/main/java/hello/HelloWorldApplication.java

package hello;

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以打开关键行为,包括配置a DispatcherServlet。但Spring Boot 在类路径上检测到spring-webmvc时会自动打开此注释。这将使您在即将到来的步骤中构建控制器。

的@SpringBootApplication也带来在@ComponentScan,这告诉Spring扫描hello包那些控制器(连同任何其他注释组件类)。

构建可执行的JAR

您可以使用Gradle或Maven从命令行运行该应用程序。或者,您可以构建一个包含所有必需依赖项,类和资源的可执行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 target / gs-actuator-service-0.1.0.jar

上面的过程将创建一个可运行的JAR。您也可以选择构建经典WAR文件。
…服务出现…
测试一下:

$ 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

... service comes up on port 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/hello/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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 hello;

import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
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 org.springframework.test.context.junit4.SpringRunner;

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

/**
 * Basic integration tests for service demo application.
 *
 * @author Dave Syer
 */
@RunWith(SpringRunner.class)
@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/info", Map.class);

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

}

摘要

恭喜!您刚刚使用Spring开发了一个简单的RESTful服务。由于Spring Boot Actuator,您添加了一些有用的内置服务。

扩展知识

注意:本示例会启动两个端口

分别是web服务的端口
server.port: 9000

Actuator服务的端口
management.server.port: 9001

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值