Spring Boot Actuator 监控

简述

spring boot actuator 是 spring boot 为监控线上项目运行指标所提供的一个 starter 模块,spring boot actuator 不跟其他模块那样主要使用于业务开发或连接一些外部资源,完全是用于暴露自身信息的模块,方便我们监控和管理线上项目

Actuator 初探

下面通过一个简单的示例,对 spring boot actuator 有一个直观的认识

使用 spring boot actuator 需引入其 starter 依赖

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

之后启动项目,发现控制台多输出了一行日志
控制台输出
日志输出信息告诉我们,应用在/actuator路径下暴露了两个端点。访问 localhost:8080/actuator 返回以下结果

{
    "_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
        },
        "info": {
            "href": "http://localhost:8080/actuator/info",
            "templated": false
        }
    }
}

这是由 spring boot actuator 为我们自动创建的监控端点,通过这些端点,我们可以获取应用的信息,还可以通过端点对我们的应用进行管理。比如 /health 端点返回程序的健康状况,可以通过访问 /actuator/health 端点

{
    "status": "UP"
}

端点(endpoint)

spring boot actuator 中,用来保存应用信息的类称之为端点(endpoint),每个端点都有一个 enable属性标记端点是否启用,只有当 enable 属性设置为 true 的时候,端点对应的示例才会在上下文中创建,并收集应用相关信息。默认情况下,除了 shutdown 端点外,其他所有端点 enable 均为 false,可通过management.endpoint.<id>.enabled 修改,如启用将 /shutdown 端点配置为:

management.endpoint.shutdown.enabled: true

spring boot actuator 中默认提供了一些端点,根据类型可以划分为

  • 应用配置 endpoint:获取程序中加载的配置信息,如:自动装配 bean 信息,环境变量等
  • 度量指标 endpoint:获取应用运行时的度量指标,如:JVM 信息、HTTP 请求信息等
  • 操作控制 endpoint:提供管理程序生命周期的接口,如:结束应用程序/shutdown

应用配置端点

由于 spring boot 改善了传统 spring 项目繁杂的 xml 配置,通过默认优于配置,是我们代码简介的同时,整个应用的配置信息和依赖关系等被分散到各个配置类上。这使得我们分析应用中资源和实例的各种关系变得非常的困难,而这类端点就可以帮助我们轻松的获取一系列关于Spring 应用配置内容的详细报告,比如:自动化配置的报告、Bean创建的报告、环境属性的报告等。

/conditions

该端点用来获取应用的自动化配置报告,其中包括所有自动化配置的候选项。同时还列出了每个候选项自动化配置的各个先决条件是否满足。所以,该端点可以帮助我们方便的找到一些自动化配置为什么没有生效的具体原因

{
    "contexts": {
        "application": {
            "positiveMatches": {
                "AuditEventsEndpointAutoConfiguration": [
                    {
                        "condition": "OnAvailableEndpointCondition",
                        "message": "@ConditionalOnAvailableEndpoint no property management.endpoint.auditevents.enabled found so using endpoint default; @ConditionalOnAvailableEndpoint marked as exposed by a 'management.endpoints.web.exposure' property"
                    }
                ]
                // ...
            },
            "negativeMatches": {
                "DataSourceAutoConfiguration": {
                    "notMatched": [
                        {
                            "condition": "OnClassCondition",
                            "message": "@ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'"
                        }
                    ],
                    "matched": []
                }
                // ...
            },
            "unconditionalClasses": [
                "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration",
                // ...
            ]
        }
    }
}
  • positiveMatches:显示条件匹配成功的自动化配置,并显示提示信息
  • negativeMatches:显示条件匹配失败的自动化配置,并显示条件不匹配原因。比如上面DataSourceAutoConfiguration没有匹配成功的原因是因为程序中找不到org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType
  • unconditionalClasses:显示无条件自动装配的类名称(如果有的话)

/beans

该端点显示应用上下文中创建的所有 bean

{
    "contexts": {
        "application": {
            "beans": {
                "endpointCachingOperationInvokerAdvisor": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
                    "resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
                    "dependencies": [
                        "environment"
                    ]
                }
            },
            // ...
            "parentId": null
        }
    }
}

每个 bean 包含一下信息:
aliases:bean 的别名
scope:bean 的作用域
type:bean 的 Java 类型
resource:class 文件的路径
dependencies:依赖的 bean 名称

/configprops

该端点显示所有由@ConfigurationProperties 注解修饰的类的列表

{
    "contexts": {
        "application": {
            "beans": {
                "management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties": {
                    "prefix": "management.endpoints.web",
                    "properties": {
                        "pathMapping": {},
                        "exposure": {
                            "include": [
                                "*"
                            ],
                            "exclude": []
                        },
                        "basePath": "/actuator"
                    }
                },
                // ...
            },
            "parentId": null
        }
    }
}

prefix :配置类的前缀
properties :各个属性的名称和值

/env

env 端点暴露应用的所有配置属性信息,该端点与 /configprops 不同,该端点不仅返回应用的配置信息,还返回了系统属性、环境变量、JVM 属性等信息,也包括应用还没有使用的配置

{
	"activeProfiles": [
		"dev"
	],
    "propertySources": [
		{
            "name": "server.ports",
            "properties": {
                "local.server.port": {
                    "value": 8080
                }
            }
        },
        {
            "name": "servletContextInitParams",
            "properties": {}
        },
        {
            "name": "systemProperties",
            "properties": {
				"os.name": {
					"value": "Mac OS X"
				}
				// ...
			}
        },
        {
            "name": "systemEnvironment",
            "properties": {
				"PATH": {
			        "value": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
			        "origin": "System Environment Property \"PATH\""
			    },
				// ...
			}
        },
        {
		    "name": "applicationConfig: [classpath:/application.yml]",
		    "properties": {
		        "management.endpoints.web.exposure.include": {
		            "value": "*",
		            "origin": "class path resource [application.yml]:5:18"
		        }
		    }
		}
	]
}

activeProfiles 程序启用的配置环境,这里是 dev 环境
propertySources 配置属性详细信息,返回应用所有配置信息

/mappings

该端点返回所有 @RequestMapping 路径的列表信息

{
	"context": {
		"application":{
			"mappings": {
				"dispatcherServlet": [
					{
					    "handler": "Actuator web endpoint 'beans'",
					    "predicate": "{GET /actuator/beans, produces [application/vnd.spring-boot.actuator.v3+json || application/vnd.spring-boot.actuator.v2+json || application/json]}",
					    "details": {
					        "handlerMethod": {
					            "className": "org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler",
					            "name": "handle",
					            "descriptor": "(Ljavax/servlet/http/HttpServletRequest;Ljava/util/Map;)Ljava/lang/Object;"
					        },
					        "requestMappingConditions": {
					            "consumes": [],
					            "headers": [],
					            "methods": [
					                "GET"
					            ],
					            "params": [],
					            "patterns": [
					                "/actuator/beans"
					            ],
					            "produces": [
					                {
					                    "mediaType": "application/vnd.spring-boot.actuator.v3+json",
					                    "negated": false
					                },
					                {
					                    "mediaType": "application/vnd.spring-boot.actuator.v2+json",
					                    "negated": false
					                },
					                {
					                    "mediaType": "application/json",
					                    "negated": false
					                }
					            ]
					        }
					    }
					},
					// ...
				],
				"servletFilters": [
					{
					    "urlPatternMappings": [
					        "/*"
					    ],
					    "servletNameMappings": [],
					    "name": "webMvcMetricsFilter",
					    "className": "org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter"
					},
					// ...
				],
				"servlets": [
					{
				        "mappings": [],
				        "name": "default",
				        "className": "org.apache.catalina.servlets.DefaultServlet"
				    },
				    // ...
				]
			},
			"parentId": null
		}
	}
}

/info

该端点用于返回一些应用的自定义信息(在 application.yml 通过 info 前缀定义的一些属性),没定义置默认返回空的 json 体。如 application.yml 文件内容如下:

info:
  name: hxy
  sex: man

访问 localhost:8080/actuator/info,返回:

{
    "name": "hxy",
    "sex": "man"
}

度量指标端点

上面介绍的应用配置端点,在应用启动的时候已经确定了其返回内容,可以说是程序的一个静态报告。而度量指示端点则是动态变化的,提供了程序运行过程中的一些指标信息,如 HTTP 请求统计,可以利用这些端点,构建一套完整的程序监控系统,监控线上系统的运行情况。引入 micrometer 模块还能添加自己指标数据,常用的端口有 /metrics /health /threaddump

/metircs

该端点用来返回当前应用的各类指标,比如内存信息、线程信息、垃圾回收信息等
访问 /actuator/metircs 返回所有指标等名称

{
    "names": [
        "jvm.threads.states",
        "process.files.max",
        "jvm.gc.memory.promoted",
        "jvm.memory.max",
        "jvm.memory.used",
        "system.load.average.1m",
        "jvm.gc.max.data.size",
        "jvm.memory.committed",
        "system.cpu.count",
        "logback.events",
        "jvm.buffer.memory.used",
        "tomcat.sessions.created",
        "jvm.threads.daemon",
        "system.cpu.usage",
        "jvm.gc.memory.allocated",
        "tomcat.sessions.expired",
        "jvm.threads.live",
        "jvm.threads.peak",
        "process.uptime",
        "tomcat.sessions.rejected",
        "process.cpu.usage",
        "http.server.requests",
        "jvm.classes.loaded",
        "jvm.classes.unloaded",
        "tomcat.sessions.active.current",
        "tomcat.sessions.alive.max",
        "jvm.gc.live.data.size",
        "process.files.open",
        "jvm.buffer.count",
        "jvm.buffer.total.capacity",
        "tomcat.sessions.active.max",
        "process.start.time"
    ]
}

访问 /actuator/metircs/{metirc-name} 即可查看具体指标详情,如 /actuator/metircs/jvm.threads.states

{
    "name": "jvm.threads.states",
    "description": "The current number of threads having TERMINATED state",
    "baseUnit": "threads",
    "measurements": [
        {
            "statistic": "VALUE",
            "value": 24
        }
    ],
    "availableTags": [
        {
            "tag": "state",
            "values": [
                "timed-waiting",
                "new",
                "runnable",
                "blocked",
                "waiting",
                "terminated"
            ]
        }
    ]
}

操作控制端点

操作控制端点用于控制应用程序,目前只有一个 /shutdowm 端点,访问该端点就能将应用程序关闭,由于该端点比较危险,所以是默认关闭的,需要指定 endpoints.shutdown.enabled=true 来开启

公众号

觉得不错可以关注我的公众号,不定时更新博客 spring boot 教程
公众号名称->簧笑语

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值