`

actuator服务监控与管理

阅读更多

引自:https://www.cnblogs.com/baidawei/p/9183531.html

 

actuator是spring 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>

如果需要访问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.yml文件中配置actuator的相关配置,其中info开头的属性,就是访问info端点中显示的相关内容,值得注意的十spring boot2.x中,默认只开放了info、health两个端点,其余的需要自己通过配置management.endpoints.web.exposure.include属性来加载(有include自然就有exclude)。如果想单独操作某个端点可以使用management.endpoint.端点.enabled属性进行启用或者禁用。

复制代码
info:
  head: head
  body: body
management:
  endpoints:
    web:
      exposure:
        #加载所有的端点,默认只加载了info、health
        include: '*'
  endpoint:
    health:
      show-details: always
    #可以关闭指定的端点
    shutdown:
      enabled: false
复制代码

 

测试

启动项目,浏览器输入:http://localhost:8088/actuator/info

{"head":"head","body":"body"}

 

自定义

  上面很多都是配置相关的,以及自带的一些端点,在实际应用中又时候默认并不能满足我们的需求。

默认装配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.spring.boot.health;

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

@Component("my1")
public class MyHealthIndicator implements HealthIndicator {
    private  static final String VERSION = "v1.0.0";
    @Override
    public Health health() {
        int code = 0;
        if(code != 0){
            Health.down().withDetail("code",code).withDetail("version",VERSION).build();
        }
        return Health.up().withDetail("code",code).withDetail("version",VERSION).up().build();
    }
}
复制代码

输入测试地址:http://localhost:8088/actuator/health

复制代码
{
    "status": "DOWN",
    "details": {
        "my1": {
            "status": "UP",
            "details": {
                "code": 0,
                "version": "v1.0.0"
            }
        },
        "rabbit": {
            "status": "DOWN",
            "details": {
                "error": "org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)"
            }
        },
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 250790436864,
                "free": 67546259456,
                "threshold": 10485760
            }
        },
        "db": {
            "status": "UP",
            "details": {
                "database": "MySQL",
                "hello": 1
            }
        },
        "redis": {
            "status": "DOWN",
            "details": {
                "error": "org.springframework.data.redis.connection.PoolException: Could not get a resource from the pool; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 10.211.55.5:6379"
            }
        }
    }
}
复制代码

可以看到当前项目的健康程度,由于没有开启linux虚拟机中的redis及rabbitMQ 所以发生异常了,平时启动项目时不去执行是不会报错的

 

健康端点(第二种方式)

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

复制代码
package com.spring.boot.health;

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

/**
 * 功能更强大,AbstractHealthIndicator实现了HealthIndicator接口
 */
@Component("my2")
public class MyAbstractHealthIndicator extends AbstractHealthIndicator {
    private static final String VERSION = "v1.0.1";
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        int code = 0;
        if(code != 0){
            builder.down().withDetail("code",code).withDetail("version",VERSION).build();
        }
        builder.withDetail("code",code).withDetail("version",VERSION).up().build();
    }
}
复制代码

测试 localhost:8088/actuator/health

复制代码
{
    "status": "DOWN",
    "details": {
        "my2": {
            "status": "UP",
            "details": {
                "code": 0,
                "version": "v1.0.1"
            }
        },
        "my1": {
            "status": "UP",
            "details": {
                "code": 0,
                "version": "v1.0.0"
            }
        },
        "rabbit": {
            "status": "DOWN",
            "details": {
                "error": "org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)"
            }
        },
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 250790436864,
                "free": 67543334912,
                "threshold": 10485760
            }
        },
        "db": {
            "status": "UP",
            "details": {
                "database": "MySQL",
                "hello": 1
            }
        },
        "redis": {
            "status": "DOWN",
            "details": {
                "error": "org.springframework.data.redis.connection.PoolException: Could not get a resource from the pool; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 10.211.55.5:6379"
            }
        }
    }
}
复制代码

 

定义自己的端点

  info、health都是spring-boot-actuator内置的,真正要实现自己的端点还得通过@Endpoint、@ReadOperator、@WriteOperation、@DeleteOperation。

不同请求的操作,调用时缺少必须参数,或者使用无法转换为所需类型的参数,则不会调用操作方法,响应状态为400(错误请求)

  @Endpoint 构建rest api的唯一路径

  @ReadOperation GET请求,响应状态为200 如果没有返回值响应404(资源未找到)

  @WriteOperation POST请求,响应状态为200如果没有返回值响应204(无响应内容)

  @DeleteOperation DELETE请求,响应状态为200如果没有返回值响应204(无响应内容)

复制代码
package com.spring.boot.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;

@Endpoint(id = "david")
public class MyEndPoint {

    @ReadOperation
    public Map<String,String> test(){
        Map<String,String> result = new HashMap<>();
        result.put("name","david");
        result.put("age","18");
        return result;
    }

}
复制代码

然后在启动类中注入bean

复制代码
package com.spring.boot;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.spring.boot.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.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

@EnableCaching
@SpringBootApplication
public class BootApplication{

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class,args);
    }

    @Configuration
    static class MyEndpointConfiguration{
        @Bean
        @ConditionalOnMissingBean
        @ConditionalOnEnabledEndpoint
        public MyEndPoint myEndPoint(){
            return new MyEndPoint();
        }
    }
}
复制代码

测试

启动项目 输入测试地址:http://localhost:8088/actuator/david

{"name":"david","age":"18"}

 

分享到:
评论

相关推荐

    springboot项目整合.zip

    第十四篇:强大的 actuator 服务监控与管理] 第十五篇:actuator与spring-boot-admin 第十六篇:定时任务详解] 第十七篇:轻松搞定文件上传] 第十八篇:轻松搞定全局异常] 第十九篇:轻松搞定数据验证

    使用SpringBoot Actuator监控应用示例

    Actuator是Spring Boot提供的对应用系统的自省和监控的集成功能,可以对应用系统进行配置查看、相关功能统计等。这篇文章主要介绍了使用SpringBoot Actuator监控应,有兴趣的可以了解一下

    Java Springboot学习资料.rar

    SpringBoot配置详解 ...actuator 服务监控与管理 actuator与spring-boot-admin 定时任务详解 文件上传 重复提交(分布式锁) 重复提交(本地锁) WebSocket 安全框架(Shiro) 分布式限流 集成hadoop、hive、oozie

    springboot+thymeleaf+actuator的demo

    通过简单的spring boot集成thymeleaf和actuator 了解springboot的默认模板thymeleaf和监控管理生产的actuator

    springboot-learning-experience:spring boot 实践学习案例

    一起来学SpringBoot | 第十四篇:强大的 actuator 服务监控与管理 一起来学SpringBoot | 第十五篇:actuator与spring-boot-admin 可以说的秘密 一起来学SpringBoot | 第十六篇:定时任务详解 一起来学SpringBoot | ...

    SpringBoot 监控管理模块actuator没有权限的问题解决方法

    主要介绍了SpringBoot 监控管理模块actuator没有权限的问题解决方法,需要的朋友可以参考下

    boot-actuator:基于SpringBoot2.0 实现的jvm远程监工图形化工具,可以同时监控多个web应用,支持远程监控

    就可以实现远程监控,和用户管理模块,动态定时任务支付windows服务器和Linux服务监控,Mac还未测试 应该也支持参考项目地址:项目框架SpringBoot 2.0.3.RELEASEmybatis-plus 3.6MySqlJdk1.8目录说明actuator-...

    基于SpringBoot3.x+Mybatis-Plus开发的通用后台管理系统源代码+数据库,简单易用,快速上手

    框架基于SpringBoot3.x开发,使用了Mybatis-Plus、dynamic-datasource多数据源、druid数据库连接池、Sa-Token权限认证、SpringDoc接口文档、lombok、actuator健康监控、retry重试等组件。 功能 通用权限管理4件套,...

    如何监控springboot的健康状况.docx

    使用Actuator检查与监控 actuaotr是spring boot项目中非常强大的一个功能,有助于对应用程序进行监控和管理,通过restful api请求来监管、审计、收集应用的运行情况,针对微服务而言它是必不可少的一个环节。

    最新SpringBoot框架后台管理模板(带权限控制)

    5.监控框架---------actuator、remote-shell 6.日志-------------logback 7.前台框架---------thymeleaf 8.生成工具---------generator(自动生成bean、mapper、SQL) 9.分页插件---------pagehelper 功能: 1....

    java利用JMX做出不一样的的JVM.docx

    最主要的还是被用来做各种监控工具,比如文章开头提到的 Spring Boot Actuator、JConsole、VisualVM 等。 JMX 既是 Java 管理系统的一个标准,一个规范,也是一个接口,一个框架。有标准、有规范是为了让开发者可以...

    SpringBoot2 基础教程,日志配置,数据源配置,事务管理等

    SpringBoot2 基础教程,日志配置,数据源配置,事务管理等。环境搭建和RestFul风格接口配置Log4j2,实现不同环境日志打印。配置系统全局异常映射...配置Actuator组件,实现系统监控。自定义启动页,项目打包指定运行环境

    Spring Boot 实战开发2022年

    │ 20 服务监控:如何使用 Actuator 组件实现系统监控?.mp4 │ 22 运行管理:如何使用 Admin Server 管理 Spring 应用程序?.mp4 │ 23 数据测试:如何使用 Spring 测试数据访问层组件?.mp4 │ 24 服务测试:...

    Spring Boot应用开发框架项目旨在简化创建产品级的Spring应用和服务.rar

    Actuator:提供生产级的监控、审计和管理功能。 配置外部化:支持多种配置文件格式,简化应用程序配置的修改和管理。 2. 快速入门:使用Spring Boot创建一个简单的RESTful API 本节将演示如何使用Spring Boot创建一...

    基于SpringBoot+Spring Cloud集成了50+个demo的项目示例.zip

    redis(redis缓存)、quartz(集群任务实现)、shiro(权限管理)、oauth2(四种认证模式)、shign(接口参数防篡改重放)、encoder(用户密码设计)、actuator(服务监控)、cloud-config(配置中心)、cloud-gateway...

    SpringBoot新手学习手册

    Actuator监控应用 38 Maven依赖 38 YML配置 39 Actuator访问路径 40 Admin-UI分布式微服务监控中心 40 Admin-UI-Server 40 Admin-UI-Client 41 十、 性能优化 43 组件自动扫描带来的问题 43 将Servlet容器...

    校园新闻发布网站使用Springboot.zip

    7. **监控与管理**:提供多种监控和管理工具,如Spring Boot Actuator,便于系统健康检查和性能监控。 8. **社区支持**:作为一个广泛使用的框架,Spring Boot拥有强大的社区支持,便于解决问题和分享经验。 通过...

    关于和spring-boot相关的demo大全

    该项目已成功集成 actuator(监控)、admin(可视化监控)、logback(日志)、aopLog(通过AOP记录web请求日志)、统一异常处理(json级别和页面级别)、freemarker(模板引擎)、thymeleaf(模板引擎)、Beetl(模板引擎)、Enjoy...

    spring boot demo 是一个用来深度学习并实战 spring boot 的项目

    该项目已成功集成 actuator(监控)、admin(可视化监控)、logback(日志)、aopLog(通过AOP记录web请求日志)、统一异常处理(json级别和页面级别)、freemarker(模板引擎)、thymeleaf(模板引擎)、Beetl(模板引擎)、Enjoy...

Global site tag (gtag.js) - Google Analytics