微服务的特色决定了功能模块的部署是分布式的,大部分功能模块都是运行在不一样的机器上,彼此经过服务调用进行交互,先后台的业务流会通过不少个微服务的处理和传递,出现异常如何快速定位便成为了一个问题,在这种框架下微服务的监控显得尤其重要。html
Spring Boot 是一个自带监控的开源框架,组件 Spring Boot Actuator 负责监控应用的各项静态和动态的变量。项目结合 Spring Boot Actuator 的使用,即可轻松对 Spring Boot 应用监控治理,Spring Boot 的 Actuator 提供了不少生产级的特性,好比监控和度量 Spring Boot 应用程序,这些特性能够经过众多 REST 接口、远程 Shell 和 JMX 得到。java
Spring Boot 使用“习惯优于配置的理念”,采用包扫描和自动化配置的机制来加载依赖 jar 中的 Spring Bean,不须要任何 XML 配置,就能够实现 Spring 的全部配置。虽然这样作能让代码变得很是简洁,可是整个应用的实例建立和依赖关系等信息都被离散到了各个配置类的注解上,这使得咱们分析整个应用中资源和实例的各类关系变得很是的困难。web
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>
添加 spring-boot-starter-web 主要是为了保持应用运行状态。redis
Spring Boot Actuator 是 Spring Boot 提供的对应用系统的检查和监控的集成功能,能够查看应用配置的详细信息,例如自动化配置信息、建立的 Spring beans 以及一些环境属性等。算法
Actuator 监控分红两类:原生端点和用户自定义端点。自定义端点主要是指扩展性,用户能够根据本身的实际应用,定义一些比较关心的指标,在运行期进行监控。spring
原生端点是在应用程序里提供众多 Web 接口,经过它们了解应用程序运行时的内部情况,原生端点又能够分红三类:数据库
Actuator 提供了 13 个接口,具体以下表所示。apache
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=beans,trace
// 设置完重启后,再次访问地址就会变成 /manage/* management.endpoints.web.base-path=/manage
health 主要用来检查应用的运行状态,这是咱们使用最高频的一个监控点,一般使用此接口提醒咱们应用实例的运行状态,以及应用不“健康”的缘由,如数据库链接、磁盘空间不够等。tomcat
默认状况下 health 的状态是开放的,添加依赖后启动项目,访问:http://localhost:8080/actuator/health
便可看到应用的状态。安全
{ "status" : "UP" }
默认状况下,最终的 Spring Boot 应用的状态是由 HealthAggregator 汇总而成的,汇总的算法是:
health 经过合并几个健康指数检查应用的健康状况。Spring Boot Actuator 有几个预约义的健康指标好比 DataSourceHealthIndicator、DiskSpaceHealthIndicator、MongoHealthIndicator、RedisHealthIndicator 等,它使用这些健康指标做为健康检查的一部分。
举个例子,若是你的应用使用 Redis,RedisHealthindicator 将被看成检查的一部分;若是使用 MongoDB,那么 MongoHealthIndicator 将被看成检查的一部分。
能够在配置文件中关闭特定的健康检查指标,好比关闭 Redis 的健康检查:
management.health.redise.enabled=false
默认全部的这些健康指标被看成健康检查的一部分。
详细的健康检查信息
默认只是展现了简单的 UP 和 DOWN 状态,为了查询更详细的监控指标信息,能够在配置文件中添加如下信息:
management.endpoint.health.show-details=always
http://localhost:8080/actuator/health
,返回信息以下:{ "status": "UP", "diskSpace": { "status": "UP", "total": 209715195904, "free": 183253909504, "threshold": 10485760 } }
其实看 Spring Boot-actuator 源码,会发现 HealthEndPoint 提供的信息不只限于此,在 org.springframework.boot.actuate.health 包下会发现 ElasticsearchHealthIndicator、RedisHealthIndicator、RabbitHealthIndicator 等。
info.app.name=spring-boot-actuator info.app.version= 1.0.0 info.app.test= test
http://localhost:8080/actuator/info
返回部分信息以下:{ "app": { "name": "spring-boot-actuator", "version": "1.0.0", "test":"test" } }
http://localhost:8080/actuator/beans
返回部分信息以下:[ { "context": "application:8080:management", "parent": "application:8080", "beans": [ { "bean": "embeddedServletContainerFactory", "aliases": [ ], "scope": "singleton", "type": "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory", "resource": "null", "dependencies": [ ] }, { "bean": "endpointWebMvcChildContextConfiguration", "aliases": [ ], "scope": "singleton", "type": "org.springframework.boot.actuate.autoconfigure.EndpointWebMvcChildContextConfiguration$$EnhancerBySpringCGLIB$$a4a10f9d", "resource": "null", "dependencies": [ ] } } ]
Spring Boot 的自动配置功能很是便利,但有时候也意味着出问题比较难找出具体的缘由。使用 conditions 能够在应用运行时查看代码了解某个配置在什么条件下生效,或者某个自动配置为何没有生效。
启动示例项目,访问网址 http://localhost:8080/actuator/conditions
返回部分信息以下:
{ "positiveMatches": { "DevToolsDataSourceAutoConfiguration": { "notMatched": [ { "condition": "DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition", "message": "DevTools DataSource Condition did not find a single DataSource bean" } ], "matched": [ ] }, "RemoteDevToolsAutoConfiguration": { "notMatched": [ { "condition": "OnPropertyCondition", "message": "@ConditionalOnProperty (spring.devtools.remote.secret) did not find property 'secret'" } ], "matched": [ { "condition": "OnClassCondition", "message": "@ConditionalOnClass found required classes 'javax.servlet.Filter', 'org.springframework.http.server.ServerHttpRequest'; @ConditionalOnMissingClass did not find unwanted class" } ] } } }
http://localhost:8080/actuator/configprops
返回部分信息以下:{ ... "environmentEndpoint": { "prefix": "endpoints.env", "properties": { "id": "env", "sensitive": true, "enabled": true } }, "spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties": { "prefix": "spring.http.multipart", "properties": { "maxRequestSize": "10MB", "fileSizeThreshold": "0", "location": null, "maxFileSize": "1MB", "enabled": true, "resolveLazily": false } }, "infoEndpoint": { "prefix": "endpoints.info", "properties": { "id": "info", "sensitive": false, "enabled": true } } ... }
展现了系统环境变量的配置信息,包括使用的环境变量、JVM 属性、命令行参数、项目使用的 jar 包等信息。和 configprops 不一样的是,configprops 关注于配置信息,env 关注运行环境信息。
启动示例项目,访问网址 http://localhost:8080/actuator/env
返回部分信息以下:
{ "profiles": [ ], "server.ports": { "local.management.port": 8088, "local.server.port": 8080 }, "servletContextInitParams": { }, "systemProperties": { "com.sun.management.jmxremote.authenticate": "false", "java.runtime.name": "Java(TM) SE Runtime Environment", "spring.output.ansi.enabled": "always", "sun.boot.library.path": "C:\\Program Files\\Java\\jdk1.8.0_101\\jre\\bin", "java.vm.version": "25.101-b13", "java.vm.vendor": "Oracle Corporation", "java.vendor.url": "http://java.oracle.com/", "java.rmi.server.randomIDs": "true", "path.separator": ";", "java.vm.name": "Java HotSpot(TM) 64-Bit Server VM", "file.encoding.pkg": "sun.io", "user.country": "CN", "user.script": "", "sun.java.launcher": "SUN_STANDARD", "sun.os.patch.level": "", "PID": "5268", "com.sun.management.jmxremote.port": "60093", "java.vm.specification.name": "Java Virtual Machine Spe
"database.password":"******"
就是 env 的扩展能够获取指定配置信息,好比http://localhost:8080/actuator/env/java.vm.version,返回 {"java.vm.version":"25.101-b13"}
http://localhost:8080/actuator/heapdump
会自动生成一个 JVM 的堆文件 heapdump,咱们可使用 JDK 自带的 JVM 监控工具 VisualVM 打开此文件查看内存快照。相似以下图:该端点用来返回基本的 HTTP 跟踪信息。默认状况下,跟踪信息的存储采用 org.springframework.boot.actuate.trace.InMemoryTraceRepository 实现的内存方式,始终保留最近的 100 条请求记录。
启动示例项目,访问网址 http://localhost:8080/actuator/httptrace
,返回信息以下:
{ "traces": [ { "timestamp": "2018-11-21T12:42:25.333Z", "principal": null, "session": null, "request": { "method": "GET", "uri": "http://localhost:8080/actuator/heapdump", "headers": { "cookie": [ "Hm_lvt_0fb30c642c5f6453f17d881f529a1141=1513076406,1514961720,1515649377; Hm_lvt_6d8e8bb59814010152d98507a18ad229=1515247964,1515296008,1515672972,1516086283; UM_distinctid=1647364371ef6-003ab9d0469ea5-b7a103e-100200-1647364371f104; CNZZDATA1260945749=232252692-1513233181-%7C1537492730" ], "accept-language": [ "zh-CN,zh;q=0.9" ], "upgrade-insecure-requests": [ "1" ], "host": [ "localhost:8080" ], "connection": [ "keep-alive" ], "accept-encoding": [ "gzip, deflate, br" ], "accept": [ "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" ], "user-agent": [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36" ] }, "remoteAddress": null }, "response": { "status": 200, "headers": { "Accept-Ranges": [ "bytes" ], "Content-Length": [ "39454385" ], "Date": [ "Wed, 21 Nov 2018 12:42:25 GMT" ], "Content-Type": [ "application/octet-stream" ] } }, "timeTaken": 1380 }, { ... }, ... ] }
http://localhost:8080/actuator/metrics
返回部分信息以下:{ "mem": 337132, "mem.free": 183380, "processors": 4, "instance.uptime": 254552, "uptime": 259702, "systemload.average": -1.0, "heap.committed": 292864, "heap.init": 129024, "heap.used": 109483, "heap": 1827840, "nonheap.committed": 45248, "nonheap.init": 2496, "nonheap.used": 44269, "nonheap": 0, "threads.peak": 63, "threads.daemon": 43, "threads.totalStarted": 83, "threads": 46, "classes": 6357, "classes.loaded": 6357, "classes.unloaded": 0, "gc.ps_scavenge.count": 8, "gc.ps_scavenge.time": 99, "gc.ps_marksweep.count": 1, "gc.ps_marksweep.time": 43, "httpsessions.max": -1, "httpsessions.active": 0 }
对 /metrics 接口提供的信息进行简单分类以下表:
解释说明
http://localhost:8080/actuator/metrics/mem.free
,返回:{"mem.free":178123}。management.endpoint.shutdown.enabled=true
shutdown 接口默认只支持 post 请求。
curl -X POST "http://localhost:8080/actuator/shutdown" { "message": "Shutting down, bye..." }
http://localhost:8080/actuator/mappings
返回部分信息以下:{ "/**/favicon.ico": { "bean": "faviconHandlerMapping" }, "{[/hello]}": { "bean": "requestMappingHandlerMapping", "method": "public java.lang.String com.neo.controller.HelloController.index()" }, "{[/error]}": { "bean": "requestMappingHandlerMapping", "method": "public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)" } }
/threaddump 接口会生成当前线程活动的快照,这个功能很是好,方便咱们在平常定位问题的时候查看线程的状况,主要展现了线程名、线程 ID、线程的状态、是否等待锁资源等信息。
启动示例项目,访问网址 http://localhost:8080/actuator/threaddump
返回部分信息以下:
[ { "threadName": "http-nio-8088-exec-6", "threadId": 49, "blockedTime": -1, "blockedCount": 0, "waitedTime": -1, "waitedCount": 2, "lockName": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@1630a501", "lockOwnerId": -1, "lockOwnerName": null, "inNative": false, "suspended": false, "threadState": "WAITING", "stackTrace": [ { "methodName": "park", "fileName": "Unsafe.java", "lineNumber": -2, "className": "sun.misc.Unsafe", "nativeMethod": true }, ... { "methodName": "run", "fileName": "TaskThread.java", "lineNumber": 61, "className": "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable", "nativeMethod": false } ... ], "lockInfo": { "className": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject", "identityHashCode": 372286721 } } ... ]
通过这节课实践咱们发现 Spring Boot Actuator 做为 Spring Boot 自带的监控组件很是强大,它能够监控和管理 Spring Boot 应用,如健康检查、审计、统计和 HTTP 追踪等,全部的这些特性能够经过 JMX 或者 HTTP endpoints 来得到。使用 Spring Boot Actuator 以后,可让咱们经过很简单的接口或者命令来查询应用的一切运行状态,从而达到对应用的运行状况了如指掌。