Spring Boot中如何使用Ostara监控应用?

在本博客中,您将了解如何使用 Ostara 监控 Spring Boot 应用程序。Ostara 是一个桌面应用程序,用于监视和管理您的应用程序。

通常使用Spring Actuator、Prometheus 和 Grafana 来监控您的应用程序,在这篇文章中,您将了解使用 Spring Actuator 与Ostara结合的替代方法。Ostara 的设置要容易一些,因此它看起来是一个有效的替代方案。

先决条件是:

  • Spring Boot 3基础知识;
  • 基本的Linux知识;
  • 使用Java 17。

创建被测应用程序
首先,您需要创建一个可以监控的应用程序:加入Spring Web 和 Spring Boot Actuator两个组件:

  1. Spring Web 将用于创建两个虚拟 Rest 端点
  2. Spring Boot Actuator 将用于启用监控端点。

在 pom 文件中添加 git-commit-id-plugin 以生成构建信息。此外,在 Spring-boot-maven-plugin 的执行中添加 build-info 目标,以便在构建过程中自动生成信息。

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>build-info</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <groupId>pl.project13.maven</groupId>
      <artifactId>git-commit-id-plugin</artifactId>
      <version>4.9.10</version>
      <executions>
        <execution>
          <id>get-the-git-infos</id>
          <goals>
            <goal>revision</goal>
          </goals>
        </execution>
      </executions>
 
      <configuration>
        <dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
        <prefix>git</prefix>
        <verbose>false</verbose>
        <generateGitPropertiesFile>true</generateGitPropertiesFile>
        <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
        <format>properties</format>
        <gitDescribe>
          <skip>false</skip>
          <always>false</always>
          <dirty>-dirty</dirty>
        </gitDescribe>
      </configuration>
 
    </plugin>
  </plugins>
</build>

在 application.properties 中为执行器端点启用完整的 git 信息。

management.info.git.mode=full

添加一个带有两个虚拟端点的 Rest 控制器:

@RestController
public class MetricsController {
  
    @GetMapping("/endPoint1")
    public String endPoint1() {
        return
"Metrics for endPoint1";
    }
  
    @GetMapping(
"/endPoint2")
    public String endPoint2() {
        return
"Metrics for endPoint2";
    }
      
}

构建运行

$ mvn clean verify
$ java -jar target/myostaraplanet-0.0.1-SNAPSHOT.jar

验证端点:
$ curl http://localhost:8080/endPoint1
Metrics for endPoint1
$ curl http://localhost:8080/endPoint2
Metrics for endPoint2

验证 actuato端点:

$ curl http://localhost:8080/actuator | python3 -mjson.tool
 ...
{
   
"_links": {
       
"self": {
           
"href": "http://localhost:8080/actuator",
           
"templated": false
        },
       
"health": {
           
"href": "http://localhost:8080/actuator/health",
           
"templated": false
        },
       
"health-path": {
           
"href": "http://localhost:8080/actuator/health/{*path}",
           
"templated": true
        }
    }
}

添加安全性
基本的安全措施已经到位。不过,还不是很安全。让我们为执行器端点添加授权。请注意,本段中的设置不适合生产使用。

在 pom 中添加 Spring Security 依赖关系。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

在 application.properties 文件中添加凭证和角色。同样,请勿将其用于生产目的。
spring.security.user.name=admin
spring.security.user.password=admin123
spring.security.user.roles=ADMIN

添加一个 WebSecurity 类,为执行器端点添加安全层。

@Configuration
@EnableWebSecurity
public class WebSecurity {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authz -> authz
                .requestMatchers("/actuator/**").hasRole("ADMIN")
                .anyRequest().permitAll())
                .httpBasic(Customizer.withDefaults());
        return http.build();
 
    }
}

构建并启动应用程序。验证是否可以使用指定的凭据访问执行器端点。

$ curl http://localhost:8080/actuator -u "admin:admin123" | python3 -mjson.tool
 ...
{
   
"_links": {
       
"self": {
           
"href": "http://localhost:8080/actuator",
           
"templated": false
        },
       
"health": {
           
"href": "http://localhost:8080/actuator/health",
           
"templated": false
        },
       
"health-path": {
           
"href": "http://localhost:8080/actuator/health/{*path}",
           
"templated": true
        }
    }
}

安装 Ostara
访问 Ostara 网站Ostara website,点击 "下载 Ostara "按钮。选择你使用的平台(我使用的是 Linux 64 位),然后下载 Ostara-0.12.0.AppImage 文件。双击该文件,Ostara 就启动了。就这样!

监控应用程序
默认情况下,只启用有限的一组执行器端点。Ostara 将通过这有限的一组端点运行,但因此可见的信息较少。要查看 Ostara 的全部功能,必须启用所有执行器端点。再次提醒,在生产过程中要注意信息的公开程度。

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

在继续使用 Ostara 之前,建议禁用发送使用统计信息和错误信息的功能。
导航至 "设置"(右上角),选择 "隐私",然后禁用跟踪选项。

在左侧菜单中选择 "创建实例",然后填写以下字段:

  • Actuator URL: http://localhost:8080/actuator
  • Alias: MyFirstInstance
  • Application Name: MyFirstApp
  • Disable SSL Verification: Yes (for this demo, no SSL connection is used)
  • Authentication Type: Basic
  • Username and Password: the admin credentials

单击 " Test Connection"按钮。这会返回一个未经授权的错误,这似乎是 Ostara 的一个错误,因为凭证信息是正确的。
忽略错误,点击保存按钮。

Ostara 可以连接到应用程序,仪表板会显示一些基本状态信息。

Info 
信息页面显示您在 git-commit-id-plugin 帮助下获得的信息。

App Properties
应用程序属性页面显示应用程序属性。不过,从下面的截图中可以看到,所有值都被屏蔽了。这是 Spring Boot 3 的默认行为。

这种行为可以在 Spring Boot 应用程序的 application.properties 中更改。您可以选择 "always "(不推荐)、"when-authorized "或 "never"。

management.endpoint.configprops.show-values=when-authorized
management.endpoint.env.show-values=when-authorized

重新构建并启动应用程序。数值可见。

Metrics
通过 "Metrics"页面,您可以启用预定义或自定义度量的通知。

打开 http.server.requests 指标,然后单击 Add Metric Notification.。

填写以下内容,以便在 EndPoint1 被调用超过 10 次时创建通知,然后单击保存按钮:

  • Name: EndPoint 1 invoked > 10 times
  • Type: Simple
  • Tags: /endPoint1
  • Operation: Greater Than
  • Value: 10

Loggers
记录仪页面会显示可用的记录仪,您可以更改所需的记录级别。当您需要分析错误时,这是一项非常有趣的功能。

单击 com.mydeveloperplanet.myostaraplanet.MetricsController 的 DEBUG 按钮。系统将显示禁止此操作的消息。

解决办法是禁用执行器端点的 csrf 保护。

在 WebSecurity 类中添加以下一行。

public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authz -> authz
            .requestMatchers("/actuator/**").hasRole("ADMIN")
            .anyRequest().permitAll())
            .csrf(csrf -> csrf
                    .ignoringRequestMatchers(
"/actuator/**")
            )
            .httpBasic(Customizer.withDefaults());
    return http.build();
}

或者
在 EndPoint1 代码中添加一些日志语句,以验证结果。

@RequestMapping("/endPoint1")
public String endPoint1() {
    logger.debug(
"This is DEBUG message");
    logger.trace(
"This is a TRACE message");
    return
"Metrics for endPoint1";
}

构建并重新启动应用程序。

再次为 MetricsController 启用 DEBUG 日志并调用 EndPoint1。日志中将显示 DEBUG 语句。

结论
Ostara 是监控 Spring Boot 应用程序的不错选择。安装时只需下载一个文件并启动即可。Ostara 能为你提供清晰的可视化视图,并在出现问题时发出通知。它还能在实例上启动线程剖析并下载堆转储。与 Grafana 相比,Grafana 的图表比 Ostara 更花哨。不过,Ostara 不仅是一款可视化工具,还能与应用程序进行交互,并在出现问题时接收通知。