使用Spring Boot执行器进行应用程序监视

2024-02-04 11:10

本文主要是介绍使用Spring Boot执行器进行应用程序监视,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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为不同的spring模块提供了一些启动器依赖性,我们可以从Spring Initializr的web和执行器模块中创建应用程序。您可以按照图像说明进行操作。我们将使用Gradle作为构建工具。
在这里插入图片描述
单击生成按钮以生成初始项目。之后,将该项目复制到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 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 {@ReadOperationpublic 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 …
在这里插入图片描述
由于我们已将管理员配置为用户名和密码,因此需要输入用户名和密码,然后单击登录按钮。如果我们提供了错误的用户名或密码,它将给出“错误的凭据” 错误。否则,请重定向到我们的愿望页面。默认情况下 /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 {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().antMatchers("/custom-path/**").hasRole("ADMIN").and().httpBasic();}@Bean@Overridepublic UserDetailsService userDetailsService() {UserDetails user =User.withUsername("admin").password(passwordEncoder().encode("admin")).roles("ADMIN").build();return new InMemoryUserDetailsManager(user);}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

使用此配置,我们可以根据需要限制特定的端点。因此,现在我们从浏览器中访问URL http:// localhost:8070 / custom-path / info,它会弹出一个凭据凭证。
在这里插入图片描述
因此,我们必须输入凭据才能访问特定的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。我们应该得到以下输出

在这里插入图片描述
我们可以添加其他信息,例如构建信息,应用程序的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 {@Overridepublic 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,并将获得以下响应。
在这里插入图片描述
因此,在这里,我们获得了包含自定义信息的所有信息。

有关/ 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 {@Overridepublic Health health() {Health health = Health.up().withDetail("Details","Server is up").build();return health;}
}

重新部署服务器后,我们可以从浏览器浏览http:// localhost:8070 / custom-path / health URL。我们将得到以下回应。
在这里插入图片描述
Spring Boot Actuator包含许多有用的端点,比我上面解释的更多。执行器在生产环境中提供了许多有用的功能。有很多事情要讨论,但是本文已经太久了。我将在下一篇文章中讨论其他一些端点和功能的详细信息。

在这里插入图片描述

这篇关于使用Spring Boot执行器进行应用程序监视的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/677291

相关文章

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构