SpringBoot 项目健康检查与监控

Spring Boot 最主要的特性就是AutoConfig(自动配置),而对于我们这些使用者来说也就是各种starter,
Spring Boot-Actuator 也提供了starter,为我们自动配置,在使用上我们只需要添加starter到我们的依赖中,然后启动项目即可。

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

常用Endpoint


Spring Boot-actuator,提供了许多有用的EndPoint,对Spring Boot应用提供各种监控,下面说一下我常用的EndPoint:

/health 应用的健康状态
/configprops 获取应用的配置信息,因为Spring Boot 可能发布时是单独的Jar包,配置文件可能包含其中, 当我们需要检查配置文件时可以使用 ConfigpropsEndPoint 进行查看一些配置是否正确。
/trace 最近几次的http请求信息

HealthEndPoint


当我们访问 http://localhost:8088/health 时,可以看到 HealthEndPoint 给我们提供默认的监控结果,包含 磁盘检测和数据库检测。

{
    "status": "UP",
    "diskSpace": {
        "status": "UP",
        "total": 398458875904,
        "free": 315106918400,
        "threshold": 10485760
    },
    "db": {
        "status": "UP",
        "database": "MySQL",
        "hello": 1
    }
}

其实看 Spring Boot-actuator 源码,你会发现 HealthEndPoint 提供的信息不仅限于此,org.springframework.boot.actuate.health 包下 你会发现 ElasticsearchHealthIndicator、RedisHealthIndicator、RabbitHealthIndicator 等
也就是 HealthEndPoint 也提供 ES, Redis 等组件的健康信息。

自定义Indicator 扩展 HealthEndPoint


看源码 其实 磁盘和数据库健康信息就是 DiskSpaceHealthIndicator、DataSourceHealthIndicator 来实现的,当我们对一些我们自定义的组件进行监控时, 我们也可以实现个Indicator :

@Component
public class User implements HealthIndicator {
    /**
     * user监控 访问: http://localhost:8088/health
     *
     * @return 自定义Health监控
     */
    @Override
    public Health health() {

        return new Health.Builder().withDetail("usercount", 10) //自定义监控内容
                .withDetail("userstatus", "up").up().build();
    }
}

这时我们再次访问: http://localhost:8088/health 这时返回的结果如下,包含了我们自定义的 User 健康信息。

{
    "status": "UP",
    "user": {
        "status": "UP",
        "usercount": 10,
        "userstatus": "up"
    },
    "diskSpace": {
        "status": "UP",
        "total": 398458875904,
        "free": 315097989120,
        "threshold": 10485760
    },
    "db": {
        "status": "UP",
        "database": "MySQL",
        "hello": 1
    }
}

自定义EndPoint


其实除了扩展 HealthEndPoint 来添加一些健康检查, 我们也可以自定定义一些EndPoint 来提供程序运行时一些信息的展示:

@Configuration
public class EndPointAutoConfig {
    @Bean
    public Endpoint<Map<String, Object>> customEndPoint() {
        return new SystemEndPoint();
    }
}


@ConfigurationProperties(prefix="endpoints.customsystem")
public class SystemEndPoint extends AbstractEndpoint<Map<String, Object>> {

    public SystemEndPoint(){
        super("customsystem");
    }
    @Override
    public Map<String, Object> invoke() {
        Map<String,Object> result= new HashMap<>();
        Map<String, String> map = System.getenv();
        result.put("username",map.get("USERNAME"));
        result.put("computername",map.get("COMPUTERNAME"));
        result.put("userdomain",map.get("USERDOMAIN"));
        return result;
    }
}

访问 http://localhost:8088/customsystem 来查看我们自定义的EndPoint ,返回结果如下:

{
    "username": "xxx",
    "userdomain": "DESKTOP-6EAN1H4",
    "computername": "DESKTOP-6EAN1H4"
}



我们在为Spring Boot应用添加actuator后,期望的health接口返回结果应该是类似下面的结果:

{
  status: "UP",
  diskSpace: 
  {
    status: "UP",
    total: 250182889472,
    free: 31169568768,
    threshold: 10485760
  },
  db: 
  {
    status: "UP",
    database: "H2",
    hello: 1
  }
}

如果只是返回了status

{
  status: "UP"
}

则需要为应用新增配置,以yml配置文件为例,需要添加如下配置:

management:
  security:
    enabled: false
endpoints:
  health:
    sensitive: false

Spring boot 2.0之后不管用。参考:https://www.jianshu.com/p/1aadc4c85f51

management.endpoint.health.show-details=always



/heapdump这个主要会dump目前堆的状况出来,可以用jvm的工具大家,并查看目前堆的状况,但是总的来说没人会这么干,会造成系统的短暂停止,大流量容易压垮系统

/health 这个路径主要是用来统计系统的状况,默认里面目前只有系统状况和磁盘状况

/info

/beans可以查看到目前Spring里面加载的所有bean,在生产中感觉没有什么用处,可能在开发中会有一些帮助,方便查看bean是否被扫描

/env里面包含了目前的环境变量,包括application.yaml配置的属性,以及systemProperties都能够拿到

/dump里面包含了目前线程的一个快照信息

/mappings 里面包含了Controller的所有mapping信息,开发中新手经常会遇到访问不到controller的情况,可以根据这个查看是否被扫描

/trace trace目前主要是监控http请求的,监控每个请求的状况,如下所示:

[
    {
        "timestamp": 1479717912091,
        "info": {
            "method": "GET",
            "path": "/",
            "headers": {
                "request": {
                    "Connection": "keep-alive",
                    "User-Agent": "GoogleSoftwareUpdateAgent/1.2.6.1370 CFNetwork/807.0.4 Darwin/16.0.0 (x86_64)",
                    "Host": "127.0.0.1:8080"
                },
                "response": {
                    "X-Application-Context": "application",
                    "Date": "Mon, 21 Nov 2016 08:45:12 GMT",
                    "Content-Type": "application/json;charset=UTF-8",
                    "status": "404"
                }
            }
        }
    },
    {
        "timestamp": 1479717910980,
        "info": {
            "method": "GET",
            "path": "/",
            "headers": {
                "request": {
                    "Connection": "keep-alive",
                    "User-Agent": "GoogleSoftwareUpdate/1.2.6.1370 CFNetwork/807.0.4 Darwin/16.0.0 (x86_64)",
                    "Host": "127.0.0.1:8080"
                },
                "response": {
                    "X-Application-Context": "application",
                    "Date": "Mon, 21 Nov 2016 08:45:10 GMT",
                    "Content-Type": "application/json;charset=UTF-8",
                    "status": "404"
                }
            }
        }
    },
    {
        "timestamp": 1479717908924,
        "info": {
            "method": "GET",
            "path": "/",
            "headers": {
                "request": {
                    "Connection": "keep-alive",
                    "User-Agent": "GoogleSoftwareUpdate/1.2.6.1370 CFNetwork/807.0.4 Darwin/16.0.0 (x86_64)",
                    "Host": "127.0.0.1:8080"
                },
                "response": {
                    "X-Application-Context": "application",
                    "Date": "Mon, 21 Nov 2016 08:45:08 GMT",
                    "Content-Type": "application/json;charset=UTF-8",
                    "status": "404"
                }
            }
        }
    },
    {
        "timestamp": 1479716651440,
        "info": {
            "method": "GET",
            "path": "/trace",
            "headers": {
                "request": {
                    "Cache-Control": "max-age=0",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                    "Upgrade-Insecure-Requests": "1",
                    "Connection": "keep-alive",
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36",
                    "Host": "localhost:8080",
                    "Accept-Encoding": "gzip, deflate, sdch, br",
                    "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"
                },
                "response": {
                    "X-Application-Context": "application",
                    "Date": "Mon, 21 Nov 2016 08:24:11 GMT",
                    "Content-Type": "application/json;charset=UTF-8",
                    "status": "200"
                }
            }
        }
    }
]

/autoconfig 显示当前SpringBoot,已经自动配置的的属性

/metrics 是整个监控里面的核心信息,


    {
        "mem": 323984,
        "mem.free": 239989,
        "processors": 4,
        "instance.uptime": 1670490,
        "uptime": 1691378,
        "systemload.average": 4.22265625,
        "heap.committed": 271872,
        "heap.init": 131072,
        "heap.used": 31882,
        "heap": 1864192,
        "nonheap.committed": 54056,
        "nonheap.init": 2496,
        "nonheap.used": 52113,
        "nonheap": 0,
        "threads.peak": 15,
        "threads.daemon": 5,
        "threads.totalStarted": 17,
        "threads": 15,
        "classes": 6662,
        "classes.loaded": 6662,
        "classes.unloaded": 0,
        "gc.ps_scavenge.count": 10,
        "gc.ps_scavenge.time": 153,
        "gc.ps_marksweep.count": 2,
        "gc.ps_marksweep.time": 150,
        "gauge.response.trace": 19,
        "gauge.response.autoconfig": 41,
        "gauge.response.error": 6,
        "gauge.response.configprops": 138,
        "counter.status.200.configprops": 1,
        "counter.status.404.error": 3,
        "counter.status.200.autoconfig": 1,
        "counter.status.200.trace": 2
    }

目前来说包含了如下信息

    The total system memory in KB (mem)
    The amount of free memory in KB (mem.free)
    The number of processors (processors)
    The system uptime in milliseconds (uptime)
    The application context uptime in milliseconds (instance.uptime)
    The average system load (systemload.average)
    Heap information in KB (heap, heap.committed, heap.init, heap.used)
    Thread information (threads, thread.peak, thread.daemon)
    Class load information (classes, classes.loaded, classes.unloaded)
    Garbage collection information (gc.xxx.count, gc.xxx.time)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354