• Java微服务监控及与普罗米修斯集成


    一、 背景说明

    Java服务级监控用于对每个应用占用的内存、线程池的线程数量、restful调用数量和响应时间、JVM状态、GC信息等进行监控,并可将指标信息同步至普罗米修斯中集中展示和报警。网上类似的文章较多,内容长且时间较旧,本文所写内容已经过实践验证,可快速帮助你实现集成。

    二、 监控方案说明

    本监控方案仅用于SpringBoot 2项目。通过在服务中引入actuator组件实现与普罗米修斯的集成。由于actuator有一定的安全隐患,本文也着重介绍了如何实现授权访问。

    三、 方案详情

    1、引入spring actuator及spring security

    Actuator用于收集微服务的监控指标包括内存使用、GC、restful接口调用时长等信息。为避免敏感信息泄露的风险,还需要同时使用spring security框架以实现访问actuator端点时的授权控制。“
    micrometer-registry-prometheus”用于将您的微服务暴露为“exportor”,可直接对接普罗米修斯。

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> <version>1.8.1</version> </dependency>

    2、配置文件(application.yml)增加应用名称

    spring: application: name: your service name

    “name”节点的值需要根据当前服务的名称填写,建议规则如下:小于32字符长度;全小写;单词间使用“-”分隔。

    3、配置文件中增加actuator配置

    建议将下面配置放在二级配置文件(application-x,例:线上配置文件“application-prod”)中。配置信息的“include”节点建议仅暴露“prometheus”节点

    #name和password为您自定义的信息 spring: security: user: name: *** password: *** management: server: port: 1234 #给actuator一个自定义端口,建议与服务的端口进行区分 metrics: tags: application: ${spring.application.name} endpoints: web: base-path: /${spring.application.name}/application-monitor #安全起见,此处使用自定义地址 exposure: include: prometheus #安全起见,仅暴露prometheus一个端点

    4、配置spring security

    为实现actuator端点访问授权,需要在启动文件(即包含“static void main”方法的文件)的同级任意目录中建立一个名为“SecurityConfig .java”的java文件,并将下列代码复制到类中

    @EnableWebSecurity @Configuration public class SecurityConfig extends 
    WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .and() .httpBasic() .and() .authorizeRequests()          //application-monitor为3小节本配置文件中自定义的actuator端点url,此处代码表示当访问actuator端点时,需要进行登录。用户名和密码参看3小节配置 .antMatchers("/**/application-monitor/**").authenticated() .anyRequest().permitAll(); //其它业务接口不用登录 } }

    5、验证结果

    配置完成后启动服务。访问服务中的查询类和命令类业务接口,应与引入“actuator”和“spring security”前一致。访问“ip:1234/{your service name}
    /application-monitor/prometheus”,应显示登录界面,如下图所示。

    输入3小节中“spring.security.user”节点中的用户名与密码,显示如下界面表示配置成功。需要注意:务必保证测试结果与上述说明一致,以避免服务正常的restful接口无法被访问。

    配置成功后,您的服务就变成了一个标准的“exportor”,可以实现与普罗米修斯的对接。

    6、附录

    如果出现POST、PUT和DELETE方法无法访问,请增加如下代码配置。

  • 相关阅读:
    3.27每日一题(常系数线性非齐次方程的特解)
    Java IO(一) File类
    大厂都是如何处理重复消息的?
    Hive 解析 JSON 字符串数据的实现方式
    win10 系统安装 doker 入门详细教程
    高级IO---五种IO模型&多路转接之Select
    前端小案例 | 一个带切换的登录注册界面(静态)
    GBase8a SSL 配置
    还没用熟 TypeScript 社区已经开始抛弃了
    竞赛 深度学习YOLO抽烟行为检测 - python opencv
  • 原文地址:https://blog.csdn.net/l688899886/article/details/125427078