使用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

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do