spring boot actuator专题

Spring Boot Actuator / Swagger

 

I'm working on Spring Boot application and i use Swagger for the documentation.html

I have adding Spring Boot Actuator on my application, but now i want to add the new services creating by actuator (/health /metrics ..) on my swagger documentation.java

I don't find how configure Actuator and Swagger.web

You can configure in Swagger which paths you wanted added to the documentation.算法

 

@Bean
public Docket appApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
                     ....

}

Will display all available endpoints.spring

.paths(PathSelectors.ant("/mypath/**"))

will limit only to endpoints exposed in mypath.数据库

 https://stackoverflow.com/questions/33673283/spring-boot-actuator-swagger

 


spring-boot-starter-actuator模块的实现对于实施微服务的中小团队来讲,
能够有效地减小监控系统在采集应用指标时的开发量。
固然,它也并非万能的,有时候咱们也须要对其作一些简单的扩展来帮助咱们实现自身系统个性化的监控需求。
下面,在本文中,咱们将详解的介绍一些关于spring-boot-starter-actuator模块的内容,包括它的原生提供的端点以及一些经常使用的扩展和配置方式。json

/autoconfig:该端点用来获取应用的自动化配置报告,其中包括全部自动化配置的候选项。
同时还列出了每一个候选项自动化配置的各个先决条件是否知足。
因此,该端点能够帮助咱们方便的找到一些自动化配置为何没有生效的具体缘由。
该报告内容将自动化配置内容分为两部分:api

positiveMatches中返回的是条件匹配成功的自动化配置
negativeMatches中返回的是条件匹配不成功的自动化配置缓存

{
    "positiveMatches": { // 条件匹配成功的
        "EndpointWebMvcAutoConfiguration": [
            {
                "condition": "OnClassCondition",
                "message": "@ConditionalOnClass classes found: 
javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet" }, { "condition": "OnWebApplicationCondition", "message": "found web application StandardServletEnvironment" } ], ... }, "negativeMatches": { // 条件不匹配成功的 "HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration": [ { "condition": "OnClassCondition", "message": "required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate" } ], ... } }

从如上示例中咱们能够看到,每一个自动化配置候选项中都有一系列的条件,
好比上面没有成功匹配的HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration配置,
它的先决条件就是须要在工程中包含org.springframework.jdbc.core.JdbcTemplate类,
因为咱们没有引入相关的依赖,它就不会执行自动化配置内容。
因此,当咱们发现有一些指望的配置没有生效时,就能够经过该端点来查看没有生效的具体缘由。安全

 

/configprops:该端点用来获取应用中配置的属性信息报告。
从下面该端点返回示例的片断中,
咱们看到返回了关于该短信的配置信息,
prefix属性表明了属性的配置前缀,
properties表明了各个属性的名称和值。
因此,咱们能够经过该报告来看到各个属性的配置路径,
好比咱们要关闭该端点,就能够经过使用endpoints.configprops.enabled=false来完成设置。

{
    "configurationPropertiesReportEndpoint": {
        "prefix": "endpoints.configprops",
        "properties": {
            "id": "configprops",
            "sensitive": true,
            "enabled": true
        }
    },
    ...
}

/env:该端点与/configprops不一样,它用来获取应用全部可用的环境属性报告。
包括:环境变量、JVM属性、应用的配置配置、命令行中的参数。
从下面该端点返回的示例片断中,
咱们能够看到它不只返回了应用的配置属性,还返回了系统属性、环境变量等丰富的配置信息,
其中也包括了应用尚未没有使用的配置。
因此它能够帮助咱们方便地看到当前应用能够加载的配置信息,
并配合@ConfigurationProperties注解将它们引入到咱们的应用程序中来进行使用。
另外,为了配置属性的安全,对于一些相似密码等敏感信息,该端点都会进行隐私保护,
可是咱们须要让属性名中包含:password、secret、key这些关键词,
这样该端点在返回它们的时候会使用*来替代实际的属性值。

 

/mappings:该端点用来返回全部Spring MVC的控制器映射关系报告。
从下面的示例片断中,咱们能够看该报告的信息与咱们在启用Spring MVC的Web应用时输出的日志信息相似,
其中
bean属性标识了该映射关系的请求处理器,
method属性标识了该映射关系的具体处理类和处理函数。

{
    "/webjars/**": {
        "bean": "resourceHandlerMapping"
    },
    "/**": {
        "bean": "resourceHandlerMapping"
    },
    "/**/favicon.ico": {
        "bean": "faviconHandlerMapping"
    },
    "{[/hello]}": {
        "bean": "requestMappingHandlerMapping",
        "method": "public java.lang.String com.didispace.web.HelloController.index()"
    },
    "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}": {
        "bean": "endpointHandlerMapping",
        "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"
    },
    ...
}


/info:该端点用来返回一些应用自定义的信息。
默认状况下,该端点只会返回一个空的json内容。
咱们能够在application.properties配置文件中经过info前缀来设置一些属性,好比下面这样:
info.app.name=spring-boot-hello
info.app.version=v1.0.0
再访问/info端点,咱们能够获得下面的返回报告,其中就包含了上面咱们在应用自定义的两个参数。

{
    "app": {
        "name": "spring-boot-hello",
        "version": "v1.0.0"
    }
}

 

度量指标类
上面咱们所介绍的应用配置类端点所提供的信息报告在应用启动的时候都已经基本肯定了其返回内容,
能够说是一个静态报告。而度量指标类端点提供的报告内容则是动态变化的,
这些端点提供了应用程序在运行过程当中的一些快照信息,
好比:内存使用状况、HTTP请求统计、外部资源指标等。
这些端点对于咱们构建微服务架构中的监控系统很是有帮助,
因为Spring Boot应用自身实现了这些端点,因此咱们能够很方便地利用它们来收集咱们想要的信息,
以制定出各类自动化策略。下面,咱们就来分别看看这些强大的端点功能。

/metrics:该端点用来返回当前应用的各种重要度量指标,好比:内存信息、线程信息、垃圾回收信息等。

{
  "mem": 541305,
  "mem.free": 317864,
  "processors": 8,
  "instance.uptime": 33376471,
  "uptime": 33385352,
  "systemload.average": -1,
  "heap.committed": 476672,
  "heap.init": 262144,
  "heap.used": 158807,
  "heap": 3701248,
  "nonheap.committed": 65856,
  "nonheap.init": 2496,
  "nonheap.used": 64633,
  "nonheap": 0,
  "threads.peak": 22,
  "threads.daemon": 20,
  "threads.totalStarted": 26,
  "threads": 22,
  "classes": 7669,
  "classes.loaded": 7669,
  "classes.unloaded": 0,
  "gc.ps_scavenge.count": 7,
  "gc.ps_scavenge.time": 118,
  "gc.ps_marksweep.count": 2,
  "gc.ps_marksweep.time": 234,
  "httpsessions.max": -1,
  "httpsessions.active": 0,
  "gauge.response.beans": 55,
  "gauge.response.env": 10,
  "gauge.response.hello": 5,
  "gauge.response.metrics": 4,
  "gauge.response.configprops": 153,
  "gauge.response.star-star": 5,
  "counter.status.200.beans": 1,
  "counter.status.200.metrics": 3,
  "counter.status.200.configprops": 1,
  "counter.status.404.star-star": 2,
  "counter.status.200.hello": 11,
  "counter.status.200.env": 1
}

从上面的示例中,咱们看到有这些重要的度量值:

系统信息:包括处理器数量processors、运行时间uptime和instance.uptime、系统平均负载systemload.average。
mem.*:内存概要信息,包括分配给应用的总内存数量以及当前空闲的内存数量。这些信息来自java.lang.Runtime。
heap.*:堆内存使用状况。这些信息来自java.lang.management.MemoryMXBean接口中getHeapMemoryUsage方法获取的java.lang.management.MemoryUsage。
nonheap.*:非堆内存使用状况。这些信息来自java.lang.management.MemoryMXBean接口中getNonHeapMemoryUsage方法获取的java.lang.management.MemoryUsage。
threads.*:线程使用状况,包括线程数、守护线程数(daemon)、线程峰值(peak)等,这些数据均来自java.lang.management.ThreadMXBean。
classes.*:应用加载和卸载的类统计。这些数据均来自java.lang.management.ClassLoadingMXBean。
gc.*:垃圾收集器的详细信息,包括垃圾回收次数gc.ps_scavenge.count、垃圾回收消耗时间gc.ps_scavenge.time、标记-清除算法的次数gc.ps_marksweep.count、标记-清除算法的消耗时间gc.ps_marksweep.time。这些数据均来自java.lang.management.GarbageCollectorMXBean。
httpsessions.*:Tomcat容器的会话使用状况。包括最大会话数httpsessions.max和活跃会话数httpsessions.active。该度量指标信息仅在引入了嵌入式Tomcat做为应用容器的时候才会提供。
gauge.*:HTTP请求的性能指标之一,它主要用来反映一个绝对数值。好比上面示例中的gauge.response.hello: 5,它表示上一次hello请求的延迟时间为5毫秒。
counter.*:HTTP请求的性能指标之一,它主要做为计数器来使用,记录了增长量和减小量。
如上示例中counter.status.200.hello: 11,它表明了hello请求返回200状态的次数为11。

对于gauge.*和counter.*的统计,这里有一个特殊的内容请求star-star,它表明了对静态资源的访问。
这两类度量指标很是有用,咱们不只可使用它默认的统计指标,还能够在程序中轻松的增长自定义统计值。
只须要经过注入org.springframework.boot.actuate.metrics.CounterService和org.springframework.boot.actuate.metrics.GaugeService来实现自定义的统计指标信息。
好比:咱们能够像下面这样自定义实现对hello接口的访问次数统计。

@RestController
public class HelloController {

    @Autowired
    private CounterService counterService;

    @RequestMapping("/hello")
    public String greet() {
        counterService.increment("didispace.hello.count");
        return "";
    }

}


/metrics端点能够提供应用运行状态的完整度量指标报告,这项功能很是的实用,
可是对于监控系统中的各项监控功能,它们的监控内容、数据收集频率都有所不一样,
若是咱们每次都经过全量获取报告的方式来收集,略显粗暴。
因此,咱们还能够经过/metrics/{name}接口来更细粒度的获取度量信息,
好比咱们能够经过访问/metrics/mem.free来获取当前可用内存数量。

/health:该端点在一开始的示例中咱们已经使用过了,它用来获取应用的各种健康指标信息。
在spring-boot-starter-actuator模块中自带实现了一些经常使用资源的健康指标检测器。
这些检测器都经过HealthIndicator接口实现,而且会根据依赖关系的引入实现自动化装配,
好比用于检测磁盘的DiskSpaceHealthIndicator、检测DataSource链接是否可用的DataSourceHealthIndicator等。
有时候,咱们可能还会用到一些Spring Boot的Starter POMs中尚未封装的产品来进行开发,
好比:当使用RocketMQ做为消息代理时,因为没有自动化配置的检测器,
因此咱们须要本身来实现一个用来采集健康信息的检测器。
好比,咱们能够在Spring Boot的应用中,
为org.springframework.boot.actuate.health.HealthIndicator接口实现一个对RocketMQ的检测器类:

@Component
public class RocketMQHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode != 0) {
          return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

      private int check() {
         // 对监控对象的检测操做
      }
}

经过重写health()函数来实现健康检查,返回的Heath对象中,共有两项内容,一个是状态信息,
除了该示例中的UP与DOWN以外,还有UNKNOWN和OUT_OF_SERVICE,能够根据须要来实现返回;
还有一个详细信息,采用Map的方式存储,在这里经过withDetail函数,注入了一个Error Code信息,咱们也能够填入一下其余信息,
好比,检测对象的IP地址、端口等。
从新启动应用,并访问/health接口,咱们在返回的JSON字符串中,将会包含了以下信息:

"rocketMQ": {
  "status": "UP"
}

/dump:该端点用来暴露程序运行中的线程信息。
它使用java.lang.management.ThreadMXBean的dumpAllThreads方法来返回全部含有同步信息的活动线程详情。

/trace:该端点用来返回基本的HTTP跟踪信息。
默认状况下,跟踪信息的存储采用org.springframework.boot.actuate.trace.InMemoryTraceRepository实现的内存方式,始终保留最近的100条请求记录。
它记录的内容格式以下:

[
    {
        "timestamp": 1482570022463,
        "info": {
            "method": "GET",
            "path": "/metrics/mem",
            "headers": {
                "request": {
                    "host": "localhost:8881",
                    "connection": "keep-alive",
                    "cache-control": "no-cache",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) 
                                    Chrome/53.0.2785.143 Safari/537.36",
                    "postman-token": "9817ea4d-ad9d-b2fc-7685-9dff1a1bc193",
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, sdch",
                    "accept-language": "zh-CN,zh;q=0.8"
                },
                "response": {
                    "X-Application-Context": "hello:dev:8881",
                    "Content-Type": "application/json;charset=UTF-8",
                    "Transfer-Encoding": "chunked",
                    "Date": "Sat, 24 Dec 2016 09:00:22 GMT",
                    "status": "200"
                }
            }
        }
    },
    ...
]


操做控制类
仔细的读者可能会发现,咱们在“初识Actuator”时运行示例的控制台中输出的全部监控端点,
已经在介绍应用配置类端点和度量指标类端点时都讲解完了。
那么还有哪些是操做控制类端点呢?
实际上,因为以前介绍的全部端点都是用来反映应用自身的属性或是运行中的状态,
相对于操做控制类端点没有那么敏感,因此他们默认都是启用的。
而操做控制类端点拥有更强大的控制能力,若是要使用它们的话,须要经过属性来配置开启。

在原生端点中,只提供了一个用来关闭应用的端点:/shutdown。咱们能够经过以下配置开启它:

endpoints.shutdown.enabled=true
在配置了上述属性以后,只须要访问该应用的/shutdown端点就能实现关闭该应用的远程操做。
因为开放关闭应用的操做自己是一件很是危险的事,
因此真正在线上使用的时候,咱们须要对其加入必定的保护机制,
好比:
定制Actuator的端点路径、整合Spring Security进行安全校验等。

http://www.open-open.com/lib/view/open1486282830132.html


SpringBoot 是为了简化 Spring 应用的建立、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让咱们能够更好的关注业务自己而不是外部的XML配置,咱们只需遵循规范,引入相关的依赖就能够轻易的搭建出一个 WEB 工程

actuatorspring boot项目中很是强大一个功能,有助于对应用程序进行监视和管理,经过 restful api 请求来监管、审计、收集应用的运行状况,针对微服务而言它是必不可少的一个环节…

Endpoints


actuator 的核心部分,它用来监视应用程序及交互,spring-boot-actuator中已经内置了很是多的 Endpoints(health、info、beans、httptrace、shutdown等等),同时也容许咱们本身扩展本身的端点

Spring Boot 2.0 中的端点和以前的版本有较大不一样,使用时需注意。另外端点的监控机制也有很大不一样,启用了不表明能够直接访问,还须要将其暴露出来,传统的management.security管理已被标记为不推荐。

内置Endpoints
id desc Sensitive
auditevents 显示当前应用程序的审计事件信息 Yes
beans 显示应用Spring Beans的完整列表 Yes
caches 显示可用缓存信息 Yes
conditions 显示自动装配类的状态及及应用信息 Yes
configprops 显示全部 @ConfigurationProperties 列表 Yes
env 显示 ConfigurableEnvironment 中的属性 Yes
flyway 显示 Flyway 数据库迁移信息 Yes
health 显示应用的健康信息(未认证只显示status,认证显示所有信息详情) No
info 显示任意的应用信息(在资源文件写info.xxx便可) No
liquibase 展现Liquibase 数据库迁移 Yes
metrics 展现当前应用的 metrics 信息 Yes
mappings 显示全部 @RequestMapping 路径集列表 Yes
scheduledtasks 显示应用程序中的计划任务 Yes
sessions 容许从Spring会话支持的会话存储中检索和删除用户会话。 Yes
shutdown 容许应用以优雅的方式关闭(默认状况下不启用) Yes
threaddump 执行一个线程dump Yes
httptrace 显示HTTP跟踪信息(默认显示最后100个HTTP请求 - 响应交换) Yes

导入依赖


在 pom.xml 中添加 spring-boot-starter-actuator 的依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注意事项

若是要访问info接口想获取maven中的属性内容请记得添加以下内容

<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>
    </plugins>
</build>

 

属性配置


在 application.properties 文件中配置actuator的相关配置,其中info开头的属性,就是访问info端点中显示的相关内容,值得注意的是Spring Boot2.x中,默认只开放了info、health两个端点,剩余的须要本身经过配置management.endpoints.web.exposure.include属性来加载(有include天然就有exclude,不作详细概述了)。若是想单独操做某个端点可使用management.endpoint.端点.enabled属性进行启用或禁用

# 描述信息 info.blog-url=https://blog.csdn.net/liupeifeng3514 info.author=WaKengMaiNi info.version=@project.version@ # 加载全部的端点/默认只加载了 info / health management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always # 能够关闭指定的端点 management.endpoint.shutdown.enabled=false # 路径映射,将 health 路径映射成 rest_health 那么在访问 health 路径将为404,由于原路径已经变成 rest_health 了,通常状况下不建议使用 # management.endpoints.web.path-mapping.health=rest_health

简单测试

启动项目,访问 http://localhost:8080/actuator/info 看到以下内容表明配置成功

{
  "blog-url": "https://blog.csdn.net/liupeifeng3514", "author": "WaKengMaiNi", "version": "0.0.1-SNAPSHOT" }

自定义 - 重点


上面讲了不少都是配置相关,以及自带的一些端点,在实际应用中有时候默认并不能知足咱们的要求,好比Spring Boot默认的健康端点就颇有可能不能知足

默认装配 HealthIndicators

下列是依赖spring-boot-xxx-starter后相关HealthIndicator的实现(经过management.health.defaults.enabled 属性能够禁用它们),但想要获取一些额外的信息时,自定义的做用就体现出来了…

名称 描述
CassandraHealthIndicator 检查 Cassandra 数据库是否启动。
DiskSpaceHealthIndicator 检查磁盘空间不足。
DataSourceHealthIndicator 检查是否能够得到链接 DataSource。
ElasticsearchHealthIndicator 检查 Elasticsearch 集群是否启动。
InfluxDbHealthIndicator 检查 InfluxDB 服务器是否启动。
JmsHealthIndicator 检查 JMS 代理是否启动。
MailHealthIndicator 检查邮件服务器是否启动。
MongoHealthIndicator 检查 Mongo 数据库是否启动。
Neo4jHealthIndicator 检查 Neo4j 服务器是否启动。
RabbitHealthIndicator 检查 Rabbit 服务器是否启动。
RedisHealthIndicator 检查 Redis 服务器是否启动。
SolrHealthIndicator 检查 Solr 服务器是否已启动。
健康端点(第一种方式)

实现HealthIndicator接口,根据本身的须要判断返回的状态是UP仍是DOWN,功能简单。

package com.lpf.chapter13.health;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

/**
 * <p>自定义健康端点</p>
 */
@Component("my1")
public class MyHealthIndicator implements HealthIndicator {

    private static final String VERSION = "v1.0.0";

    @Override
    public Health health() {
        int code = check();
        if (code != 0) {
            Health.down().withDetail("code", code).withDetail("version", VERSION).build();
        }
        return Health.up().withDetail("code", code)
                .withDetail("version", VERSION).up().build();
    }

    private int check() {

        return 0;
    }
}
 

简单测试

启动项目,访问 http://localhost:8080/actuator/health 看到以下内容表明配置成功

{
  "status": "UP", "details": { "my1": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "diskSpace": { "status": "UP", "details": { "total": 112090574848, "free": 54290890752, "threshold": 10485760 } } } }

 

健康端点(第二种方式)

继承AbstractHealthIndicator抽象类,重写doHealthCheck方法,功能比第一种要强大一点点,默认的DataSourceHealthIndicator 、 RedisHealthIndicator 都是这种写法,内容回调中还作了异常的处理。

package com.lpf.chapter13.health; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; /** * <p>自定义健康端点</p> * <p>功能更增强大一点,DataSourceHealthIndicator / RedisHealthIndicator 都是这种写法</p> */ @Component("my2") public class MyAbstractHealthIndicator extends AbstractHealthIndicator { private static final String VERSION = "v1.0.0"; @Override protected void doHealthCheck(Health.Builder builder) throws Exception { int code = check(); if (code != 0) { builder.down().withDetail("code", code).withDetail("version", VERSION).build(); } builder.withDetail("code", code) .withDetail("version", VERSION).up().build(); } private int check() { return 0; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

简单测试

启动项目,访问 http://localhost:8080/actuator/health 看到以下内容表明配置成功

{
  "status": "UP", "details": { "my2": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "my1": {...}, "diskSpace": {...} } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
定义本身的端点

上面介绍的 infohealth 都是spring-boot-actuator内置的,真正要实现本身的端点还得经过@Endpoint、 @ReadOperation@WriteOperation@DeleteOperation

注解介绍

不一样请求的操做,调用时缺乏必需参数,或者使用没法转换为所需类型的参数,则不会调用操做方法,响应状态将为400(错误请求)

  • @Endpoint 构建 rest api 的惟一路径
  • @ReadOperation GET请求,响应状态为 200 若是没有返回值响应 404(资源未找到)
  • @WriteOperation POST请求,响应状态为 200 若是没有返回值响应 204(无响应内容)
  • @DeleteOperation DELETE请求,响应状态为 200 若是没有返回值响应 204(无响应内容)
package com.lpf.chapter13.endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import java.util.HashMap; import java.util.Map; /** * <p>@Endpoint 是构建 rest 的惟一路径 </p> * 顾名思义就是不一样请求的操做,调用时缺乏必需参数,或者使用没法转换为所需类型的参数,则不会调用操做方法,响应状态将为400(错误请求) * <P>@ReadOperation = GET 响应状态为 200 若是没有返回值响应 404(资源未找到) </P> * <P>@WriteOperation = POST 响应状态为 200 若是没有返回值响应 204(无响应内容) </P> * <P>@DeleteOperation = DELETE 响应状态为 200 若是没有返回值响应 204(无响应内容) </P> */ @Endpoint(id = "lpf") public class MyEndPoint { @ReadOperation public Map<String, String> hello() { Map<String, String> result = new HashMap<>(); result.put("author", "lpf"); result.put("age", "24"); result.put("email", "XXXXXXXXXX@qq.com"); return result; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

觉得这就大功告成了吗,现实告诉个人是spring-boot默认是不认识这玩意的,得申明成一个Bean(请看 主函数

主函数
package com.lpf.chapter13; import com.lpf.chapter13.endpoint.MyEndPoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @SpringBootApplication public class Chapter13Application { public static void main(String[] args) { SpringApplication.run(Chapter13Application.class, args); } @Configuration static class MyEndpointConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public MyEndPoint myEndPoint() { return new MyEndPoint(); } } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
测试

完成准备事项后,启动Chapter13Application 访问 http://localhost:8080/actuator/battcn 看到以下内容表明配置成功…

{
  "author": "lpf", "age": "24", "email": "XXXXXXXXXX@qq.com" }
  • 1
  • 2
  • 3
  • 4
  • 5

总结


参考文档:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready

目前不少大佬都写过关于 SpringBoot 的教程了,若有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.2.RELEASE编写,包括新版本的特性都会一块儿介绍…

https://blog.csdn.net/liupeifeng3514/article/details/80558414

 

 

前言
主要是完成微服务的监控,完成监控治理。能够查看微服务间的数据处理和调用,当它们之间出现了异常,就能够快速定位到出现问题的地方。

springboot - version: 2.0
正文
依赖
maven 项目 在 pom.xml 文件中加入 actuator 的依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1
2
3
4
使用 Gradle 构建:

dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
1
2
3
配置
须要注意的是 Spring Boot 2.0 相对于上个版本, Actuator 发生不少变化,

keys 的配置改变
旧的属性 新的属性
endpoints.<id>.* management.endpoint.<id>.*
endpoints.cors.* management.endpoints.web.cors.*
endpoints.jmx.* management.endpoints.jmx.*
management.address management.server.address
management.context-path management.server.servlet.context-path
management.ssl.* management.server.ssl.*
management.port management.server.port
基本路径
全部 endpoints 默认状况下都已移至 /actuator。就是多了跟路径 actuator ;

上个版本中的 management/context-path: 和 management/port: 改成 :

management:
server:
port: 8004
servlet:
context-path: /xxx # 只有在设置了 management.server.port 时才有效
1
2
3
4
5
另外,您还可使用新的单独属性 management.endpoints.web.base-path 为管理端点设置基本路径。

例如,若是你设置management.server.servlet.context-path=/management和management.endpoints.web.base-path=/application,你就能够在下面的路径到达终点健康:/management/application/health。

若是你想恢复 1.x 的行为(即具备/health代替/actuator/health),设置如下属性:management.endpoints.web.base-path=/

ENDPOINTS
1.X 的时候属性:

HTTP 方法 路径 描述
GET /autoconfig 提供了一份自动配置报告,记录哪些自动配置条件经过了,哪些没经过
GET /configprops 描述配置属性(包含默认值)如何注入Bean
GET /beans 描述应用程序上下文里所有的Bean,以及它们的关系
GET /dump 获取线程活动的快照
GET /env 获取所有环境属性
GET /env/{name} 根据名称获取特定的环境属性值
GET /health 报告应用程序的健康指标,这些值由HealthIndicator的实现类提供
GET /info 获取应用程序的定制信息,这些信息由info打头的属性提供
GET /mappings 描述所有的URI路径,以及它们和控制器(包含Actuator端点)的映射关系
GET /metrics 报告各类应用程序度量信息,好比内存用量和HTTP请求计数
GET /metrics/{name} 报告指定名称的应用程序度量值
POST /shutdown 关闭应用程序,要求endpoints.shutdown.enabled设置为true
GET /trace 提供基本的HTTP请求跟踪信息(时间戳、HTTP头等)
2.0 部分更改:

1.x 端点 2.0 端点(改变)
/actuator 再也不可用。 可是,在 management.endpoints.web.base-path 的根目录中有一个映射,它提供了到全部暴露端点的连接。
/auditevents 该after参数再也不须要
/autoconfig 重命名为 /conditions
/docs 再也不可用
/health 如今有一个 management.endpoint.health.show-details 选项 never, always, when-authenticated,而不是依靠 sensitive 标志来肯定 health 端点是否必须显示所有细节。 默认状况下,/actuator/health公开而且不显示细节。
/trace 重命名为 /httptrace
默认端点 path 前面多了一级 /actuator 。

同时注意只有端点/health和/info端点是暴露的。

Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include info, health
1. 您能够按以下方式公开全部端点:management.endpoints.web.exposure.include=*
2. 您能够经过如下方式显式启用/shutdown端点:management.endpoint.shutdown.enabled=true
3. 要公开全部(已启用)网络端点除env端点以外:

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env
1
2
例如:

我如今开启全部的端点:

management:
endpoints:
web:
exposure:
include: "*" # * 在yaml 文件属于关键字
1
2
3
4
5
执行 localhost:${port}/actuator,能够看到全部能够执行查看的端点监控的 Url,而后咱们尝试执行关闭应用进程的指令:shutdown:

 

端点格式
/actuator/mappings 端点大改变
JSON 格式已经更改成如今正确地包含有关上下文层次结构,多个DispatcherServlets,部署的 Servlet 和 Servlet 过滤器的信息。详情请参阅#9979。
Actuator API 文档的相关部分提供了一个示例文档。

/actuator/httptrace 端点大改变
响应的结构已通过改进,以反映端点关注跟踪 HTTP 请求 - 响应交换的状况。

总结
主要是 Spring Boot 2.0 版本升级在 Actuator 上面有许多改动,须要记录下。

参考文章Part V. Spring Boot Actuator: Production-ready featuresSpring Boot 2.0系列文章(一):Spring Boot 2.0 迁移指南--------------------- 做者:KronChan 来源:CSDN 原文:https://blog.csdn.net/qq_35915384/article/details/80203768 版权声明:本文为博主原创文章,转载请附上博文连接!

相关文章
相关标签/搜索