Spring Boot Actuator是Spring Boot内置的模块,具有许多功能,可轻松管理和监视应用程序。
监视生产是软件服务提供商的重要组成部分。许多公司提供监视系统以维护生产环境。Spring Boot带有不同的功能强大的模块,开发人员可以使用它们轻松配置和维护开发及生产环境。执行器模块具有生产就绪功能,通过这些功能我们可以轻松维护生产环境。执行器公开了JMX和HTTP端点。

特征

端点: Spring Boot Actuator提供了一些默认端点,我们可以通过它们访问应用程序信息。我们还可以使用这些端点监视生产环境。端点也可以通过第三方监视工具进行访问。

指标: 我们可以使用Spring Boot执行器端点访问与OS和JVM相关的信息。这对于运行时环境非常有用。弹簧启动执行器通过与测微计应用程序监视集成来提供此功能。

审核: Spring Boot Actuator将事件发布到 AuditEventRepository。默认情况下,Spring安全性发布“身份验证成功”,“失败”和“访问被拒绝”异常。这对于报告和身份验证失败非常有用。可以通过AuditEventRepository启用审核。默认情况下,spring-boot提供InMemoryAuditEventRepository进行审核,但功能有限。

HTTP跟踪: Spring Boot执行器还提供HTTP跟踪功能。如果要使用它,则必须包含Web端点。Http跟踪提供有关请求-响应交换的信息。

重要端点

Spring Boot Actuator提供了列出的HTTP和JMX端点。我们将在本文的后面部分详细讨论。

spring boot durid 开启监控页面 spring boot中的监视器_应用程序


建筑工程

我们知道Spring Boot为不同的spring模块提供了一些启动器依赖性,我们可以从Spring Initializr的web和执行器模块中创建应用程序。您可以按照图像说明进行操作。我们将使用Gradle作为构建工具。

spring boot durid 开启监控页面 spring boot中的监视器_spring boot_02


单击生成按钮以生成初始项目。之后,将该项目复制到PC上的某个位置并解压缩。转到项目的根目录并打开终端。您的初始构建文件类似于以下代码。

Groovy

plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}
group = 'com.sanju'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
test {
    useJUnitPlatform()
}

所以现在我们将部署该项目。gradle bootrun从终端运行 。使用默认配置,应用程序将在具有管理路径/执行器的 8080端口上运行。 部署完成后,我们将从浏览器浏览URL http:// localhost:8080 / actuator /。在默认配置下,执行器模块公开了四个端点,我们可以将其视为响应。

JSON格式

// 20200222142835
// http://localhost:8080/actuator/
{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "health-path": {
      "href": "http://localhost:8080/actuator/health/{*path}",
      "templated": true
    },
    "health": {
      "href": "http://localhost:8080/actuator/health",
      "templated": false
    },
    "info": {
      "href": "http://localhost:8080/actuator/info",
      "templated": false
    }
  }
}

Spring Boot Actuator模块提供了通过在application.properties文件中添加一些属性来更改管理端口和路径的功能。因此,我们将以下代码行添加到application.properties文件。

属性文件

management.endpoints.web.base-path=/custom-path
management.server.port=8070

在部署了这些更改之后,我们将获得与http:// localhost:8070 / custom-path / URL 相同的输出。

公开端点
使用默认配置,我们只能访问四个端点,但是Spring Actuator拥有更多的端点,例如度量,HTTP跟踪,审计事件等。如果要访问此类端点,则需要对其进行配置。Spring Boot执行器提供了一些配置,以包含和排除用户端点。这是application.properties文件的示例。

management.endpoints.web.base-path=/custom-path
management.server.port=8070
management.endpoints.jmx.exposure.include=*
management.endpoints.jmx.exposure.exclude=health, metrics
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=health, metrics

使用此属性文件进行部署后,我们将检查不同的端点。我们可以看到,如果没有运行状况和指标终结点,则最大终结点将起作用。为了使所有端点都可行,我们需要添加更多与特定端点相关的配置。如果我们点击http:// localhost:8070 / custom-path /,我们可以看到执行器暴露了端点。

spring boot durid 开启监控页面 spring boot中的监视器_spring_03


在这里,我们可以看到缺少运行状况和指标终结点,因为我们随后将其从配置中排除了。

添加自定义端点
Spring Boot Actuator提供了从我们可以看到自己的定制应用程序数据的位置写入定制端点的工具。例如,我正在使用自定义终结点来检查我的服务器地址,在哪个OS中部署的服务器,服务器的MAC地址以及服务器计算机中安装的Java版本。

package com.sanju.actuatordemo.core;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Endpoint(id = "server-info")
public class ServerInfoActuatorEndpoint {
    @ReadOperation
    public List<String> getServerInfo() {
        List<String> serverInfo = new ArrayList<String>();
        try {
            serverInfo.add("Server IP Address : " + InetAddress.getLocalHost().getHostAddress());
            serverInfo.add("Host Name: " + InetAddress.getLocalHost().getHostName());
            serverInfo.add("Server OS : " + System.getProperty("os.name").toLowerCase());
            NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            byte[] mac = network.getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            serverInfo.add("Hardware Address : "+ sb.toString());
            serverInfo.add("Java Version : "+getJavaVersion());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverInfo;
    }

    private int getJavaVersion() {
        String version = System.getProperty("java.version");
        if(version.startsWith("1.")) {
            version = version.substring(2, 3);
        } else {
            int dot = version.indexOf(".");
            if(dot != -1) { version = version.substring(0, dot); }
        } return Integer.parseInt(version);
    }
}

Spring Boot Actuator提供了一些注释,通过这些注释我们刚刚配置了系统。 @Endpoint注释启用它作为一个端点和注释 @WriteOperation , @ReadOperation , @DeleteOperation像POST,GET,在HTTP动词DELETE操作执行。在这里,我们只使用了 @ReadOperation 注释。因此,如果现在重新部署应用程序并使用URL http:// localhost:8070 / custom-path / server-info进行命中,我们将得到以下输出。

JSON格式

// 20200222160924
// http://localhost:8070/custom-path/server-info
[
  "Server IP Address : 192.168.0.177",
  "Host Name: Sanjoys-MacBook-Pro.local",
  "Server OS : mac os x",
  "Hardware Address : A4-5E-60-F2-07-51",
  "Java Version : 8"
]

带执行器的弹簧安全
Spring Boot Actuator公开了一些非常敏感的端点。这些端点包含许多与系统和核心应用程序相关的信息,例如bean,指标和与配置有关的信息。因此,我们必须限制端点的访问。为此,我们可以使用Spring安全性。Spring Boot Actuator提供了弹簧安全性的自动配置。为了确保端点安全,我们必须在build.properties文件中添加以下依赖项。

Groovy

compile 'org.springframework.boot:spring-boot-starter-security'

要定义用户名和密码,我们需要在application.properties文件中添加以下几行。

Groovy

spring.security.user.name=admin
spring.security.user.password=admin

Spring Boot Actuator安全性自动配置已完成。我们需要再次重新启动服务器以启用Spring安全性。重新部署应用程序后,我们必须点击http:// localhost:8070 / custom-path / server-info。URL将被重定向到http:// localhost:8070 / login …

spring boot durid 开启监控页面 spring boot中的监视器_spring boot_04


由于我们已将管理员配置为用户名和密码,因此需要输入用户名和密码,然后单击登录按钮。如果我们提供了错误的用户名或密码,它将给出“错误的凭据” 错误。否则,请重定向到我们的愿望页面。默认情况下 /info ,/ health端点不受限制。我们可以访问没有凭据的用户。

从Spring Boot 2开始,我们可以通过扩展WebSecurityConfigurerAdapter 类来使用Spring安全性配置终结点安全性配置 。我创建了一个 SecurityConfig 扩展 WebSecurityConfigurerAdapter 和覆盖configure和 userDetailsService method的类。我还包括了bcrypt编码器作为密码编码器。
Java

package com.sanju.actuatordemo.core;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
	http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
                .antMatchers("/custom-path/**").hasRole("ADMIN")
                .and()
                .httpBasic();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withUsername("admin")
                        .password(passwordEncoder().encode("admin"))
                        .roles("ADMIN")
                        .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

使用此配置,我们可以根据需要限制特定的端点。因此,现在我们从浏览器中访问URL http:// localhost:8070 / custom-path / info,它会弹出一个凭据凭证。

spring boot durid 开启监控页面 spring boot中的监视器_spring boot_05


因此,我们必须输入凭据才能访问特定的URL,否则我们将收到403未经授权的响应。请允许我们从Spring Security获得更多详细信息。

有关/ info端点的更多信息
通过 /info 端点,我们希望获得有关应用程序的基本信息。例如,我们可以通过将其定义为application.properties文件来定义有关该应用程序的静态属性。

info.app.name=Spring Boot actuator Test Application
info.app.description=Sample application for article
info.app.version=1.0.0

添加此配置后,我们可以浏览http:// localhost:8070 / custom-path / info URL。我们应该得到以下输出

spring boot durid 开启监控页面 spring boot中的监视器_spring_06


我们可以添加其他信息,例如构建信息,应用程序的git信息。因此,我们必须将以下代码行添加到build.properties文件。对于构建信息,我们必须添加 。

Groovy

springBoot {
    buildInfo()
}

对于git信息,我们必须通过执行git init命令初始化git仓库,然后分别通过执行git add -A,git commit -m“ Initial commit”来添加文件并提交到git。然后将以下插件添加到build.properties。
Groovy

plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    //添加了插件以访问git信息  
    id "com.gorylenko.gradle-git-properties" version "1.5.1"
    id 'java'
}

我们刚刚完成了针对不同应用程序信息的配置。

通过使用InfoContributor 界面,我们可以看到应用程序的自定义信息 。我们将CustomInfoContributor.java通过实现InfoIndicator进行创建 。
Java

package com.sanju.actuatordemo.core;

import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

@Component
public class CustomInfoContributor  implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("customInfo","This is custom info indicator. You can add your application data. " +
                "You can share application persistent data from here");
    }
}

因此,我们将从浏览器中访问http:// localhost:8070 / custom-path / info URL,并将获得以下响应。

spring boot durid 开启监控页面 spring boot中的监视器_java_07


因此,在这里,我们获得了包含自定义信息的所有信息。

有关/ health端点的更多信息
使用默认配置,运行状况端点将返回有关服务器已启动或已关闭的唯一信息。但是我们也可以通过将以下代码行添加到application.properties文件中来检查详细信息。此处的值可以在授权时,始终或永远不 反对密钥management.endpoint.health.show-details。

management.endpoint.health.show-details=always

我们还可以添加带有详细信息响应的自定义健康信息的详细信息。这就是为什么我们必须添加一个将实现接口的自定义类的原因 。HealthIndicator

java

package com.sanju.actuatordemo.core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator  implements HealthIndicator {

    @Override
    public Health health() {
        Health health = Health.up().withDetail("Details","Server is up").build();
        return health;
    }
}

重新部署服务器后,我们可以从浏览器浏览http:// localhost:8070 / custom-path / health URL。我们将得到以下回应。

spring boot durid 开启监控页面 spring boot中的监视器_java_08


Spring Boot Actuator包含许多有用的端点,比我上面解释的更多。执行器在生产环境中提供了许多有用的功能。有很多事情要讨论,但是本文已经太久了。我将在下一篇文章中讨论其他一些端点和功能的详细信息。