Use Spring Boot Actuator building RESTful Web Applications

 

Spring Boot Actuator  is a sub-project of the Spring Boot. Through it, it can be easily applied to a variety of production-level services. In this tutorial, you will build an application through to learn how to add these services.

1. What you need to build

This tutorial will take you to create a "hello world" using the Boot Actuator the Spring  RESTful Web services . You need to build a HTTP GET request services:

$ curl http://localhost:9000/hello-world
复制代码

Returns the following  JSON :

{"id":1,"content":"Hello, World!"}
复制代码

They also adds a lot to your application out of the box ready to use, can be produced (or other) functions in environmental management services. You build a service, its business functions and  build RESTful Web application  consistent with the results of the tutorial. Although the comparison may be interesting, but there is no need to learn and learn this tutorial.

1.1. What you need to prepare

2. How to complete this tutorial

Like most  Spring Getting Started  Like, you can start from scratch and the completion of each step, you can skip already familiar with the basic configuration link. Anyway, will eventually get the code works properly.

From the beginning, the venue and  use Gradle build  section

Skip basic link, follow these steps:

  • Download  and extract the source code for this tutorial, or  Git  for clone: git clone https://github.com/spring-guides/gs-actuator-service.git
  • Enter the  gs-actuator-service/initial directory
  • Skip forward to  create a performance class  sections

After completion, according  gs-actuator-service/complete to the check result code directory.

3. Use Gradle build

First, set up a basic build script. When building applications using Spring, you can use whatever you like to build a program. Code contained herein is required by  Gradle  or  Maven  to run. If you are not familiar with them, see  Use Gradle to build Java projects  or  built with Maven Java project .

3.1. Creating the directory structure

In the working directory, create a subdirectory structure shown below; e.g., in a UNIX-like systems, use  mkdir -p src/main/java/hello the command to create.

└── src
    └── main
        └── java
            └── hello
复制代码

3.2. Creating Gradle build script

The following is a  Gradle build script to initialize :

build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { baseName = 'gs-actuator-service' version = '0.1.0' } sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-actuator") testCompile("org.springframework.boot:spring-boot-starter-test") testCompile("junit:junit") } 复制代码

Spring Boot Gradle plugin  provides many convenient features:

  • Bringing together all the jar packages dependent under the classpath, and build an executable monomer "über-jar", which will allow you to perform and transport services become more convenient.
  • Search  public static void main() class method is located, and mark it as executable class.
  • Provide a built-  Spring Boot dependence  dependency resolver to match the version number of the collection. You can rewrite any version, but it defaults to a collection Spring Boot version number selected.

4. built with Maven

First, set up a basic build script. When building applications using Spring, you can use whatever you like to build a program. Code contained herein is needed by  Maven  to run. If you're not familiar with it, see  built with Maven Java project .

4.1. Creating the directory structure

In the working directory, create a subdirectory structure shown below; e.g., in a UNIX-like systems, use  mkdir -p src/main/java/hello the command to create.

└── src
    └── main
        └── java
            └── hello
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>gs-actuator-service</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 复制代码

Spring Boot Maven plugin  provides many convenient features:

  • Bringing together all the jar packages dependent under the classpath, and build an executable monomer "über-jar", which makes the implementation and transfer your service more convenient.
  • Search  public static void main() class method is located, and mark it as executable class.
  • Provide a built-  Spring Boot dependence  dependency resolver to match the version number of the collection. You can rewrite any version, but it defaults to a collection Spring Boot version number selected.

5. Construction IDE

6. Run empty Service

For starters, here's a blank Spring MVC application.

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 Notes provides some default value (such as embedded Servlet container) and, of course, depending on the contents of your classpath and other content. At the same time, also opens the Spring MVC  @EnableWebMvc annotations to activate the Web endpoint.

The program does not define any endpoint, but it is up and observe some of the features Actuator enough. SpringApplication.run() Command knows how to start the Web application. You only need to run this command.

$ ./gradlew clean build && java -jar build/libs/gs-actuator-service-0.1.0.jar
复制代码

You almost did not write any code, the result of what happens? After a good start and other services, open another terminal Terminal for testing:

$ curl localhost:8080
{"timestamp":1384788106983,"error":"Not Found","status":404,"message":""}
复制代码

The server is running, and you did not define any service endpoints. You can see from the Actuator  /error common JSON response endpoint, rather than the default container HTML error response generated. You can see in the console log service starts in which the exposed end out of the box. E.g:

$ curl localhost:8080/actuator/health
{"status":"UP"}
复制代码

Good, service is already "UP".

View  Spring Boot Actuator project  for more details.

7. Create performance class

First, consider your API would look like.

You want to deal with  /hello-world when the GET request, you can use the name query parameters. In response to such a request, you will return to the following JSON represent a greeting.

{
    "id": 1,
    "content": "Hello, World!"
}
复制代码

id Field is the unique identifier greeting, the content field is a text representation of greeting.

Creates a class to represent modeling of greeting:

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; } } 复制代码

Now, you can create a controller endpoint for the performance of such services.

8. Create Resource Controller

In Spring, REST endpoint is Spring MVC controller. The following Spring MVC controller handles the  /hello-world GET request and returns  Greeting resources:

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)); } } 复制代码

The key difference between user-oriented REST endpoint controller and the controller is how to create a response. The controller does not rely on end view (e.g., JSP) model data to render the HTML, but simply the data to be written directly back to the body of the response.

@ResponseBody Annotation tells Spring MVC model will not render to view, but would object to return a written response body. This step rendered Spring message will be achieved through the converter. Jackson 2 was in the classpath, this means that if  Accept the request header specifies should return JSON, MappingJackson2HttpMessageConverter will handle the conversion between the Greeting to JSON.

How do I know Jackson 2 in the classpath it? Operation  mvn dependency:tree or  ./gradlew dependencues command to get detailed dependency tree and displays Jackson 2.x. You can see it from  Spring-Boot-Starter-JSON , which is a  spring-boot-starter-web  -dependent import.

9. Create an executable main class

You can start applications from custom main class, or may be configured from one class to do this directly. The easiest way is to use the  SpringApplication helper class:

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

}
复制代码

In the traditional Spring MVC application, you need to add  @EnableWebMvc to open the notes include  DispatcherServletkey features, including. When Spring Boot spring-webmvc detected in the classpath, it will automatically open the annotation. This will allow you to build a controller more easily in the next step.

@SpringBootApplication Also introduces  @ComponentSacn annotations to tell Spring scanning  hello package, and load those controllers (as well as others are marked annotated component class).

10. Build Executable JAR

You can run the application from the command line by Gradle or Maven, you can build and run a contains the necessary dependent, executable JAR package classes and resource files. This will make the entire development life cycle, across different environments, application publishing, version and deployment easier.

If you are using the Gradle, you can  ./gradlew bootRun start the application; also be  ./gradlew buildconstructed JAR package, and run through the following command:

java -jar build/libs/gs-actuator-service-0.1.0.jar
复制代码

If you are using Maven, the can  ./mvnw spring-boot:run to start the application; also be  ./mvnw clean package constructed JAR package, and run through the following command:

java -jar target/gs-actuator-service-0.1.0.jar
复制代码

Both ways will create an executable JAR package, you can also  build a classic WAR package .

... service comes up ...
复制代码

have a test:

$ curl localhost:8080/hello-world
{"id":1,"content":"Hello, Stranger!"}
复制代码

11. Switch to a different port

Spring Boot Actuator runs by default on port 8080 by adding a  application.properties can overwrite the configuration file.

src/main/resources/application.properties
server.port: 9000
management.server.port: 9001
management.server.address: 127.0.0.1
复制代码

Restart the application:

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

... service comes up on port 9000 ...
复制代码

have a test:

$ 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"} 复制代码

12. Test Application

Unit in order to check whether the application can be run properly, you should write an application / integration test class. Test cases can refer to the following:

  • The controller is normal
  • Endpoint Management is normal

As in the test class have seen, we start the application in a random port.

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
 *
 *      https://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); } } 复制代码

13. summary

Congratulations, you have been using Spring has developed a simple RESTful service. Because Spring Boot Actuator, you add some useful built-in services.

14. Reference

The following tutorial might be helpful to you:

Want to write a new tutorial is perfect for existing or tutorial? Please see our  contribution guidelines .

All tutorials are published code provides ASLv2 license agreement, providing for the text  CC BY-ND 3.0  license.


Original: spring.io/guides/gs/a...

Author: spring.io

Translator: Wan wanted

 

Guess you like

Origin www.cnblogs.com/liululee/p/11118573.html