欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

教你開發(fā)腳手架集成Spring?Boot?Actuator監(jiān)控的詳細(xì)過程

 更新時(shí)間:2022年05月01日 09:39:28   作者:lakernote  
這篇文章主要介紹了開發(fā)腳手架集成Spring?Boot?Actuator監(jiān)控的詳細(xì)過程,集成包括引入依賴配置文件及訪問驗(yàn)證的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

集成

引入依賴

在項(xiàng)目的pom.xml中增加以下依賴

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

配置文件

application.yml

management:
   # 禁用執(zhí)行器端點(diǎn)的安全檢查
   security:
      enabled: false

訪問驗(yàn)證

例如,輸入http://localhost:8080/actuator/health,我們可以查看應(yīng)用程序當(dāng)前狀態(tài)

{
    "status": "UP"
}

這個(gè)接口經(jīng)常用于服務(wù)探活或者健康檢查接口。

到這里就集成完成了哈。

端點(diǎn) Endpoints

Actuator默認(rèn)把所有訪問點(diǎn)暴露給JMX,但處于安全原因,只有healthinfo會(huì)暴露給Web。

Actuator提供的所有訪問點(diǎn)均在官方文檔列出,要暴露更多的訪問點(diǎn)給Web,需要在application.yml中加上配置:

management:
  endpoints:
    web:
      exposure:
        # 包含所有端點(diǎn)使用 "*",注意有引號(hào)
        include: info, health, beans, env, metrics

Actuator 提供了以下接口,具體如下表所示。

HTTP 方法路徑描述
GET/auditevents顯示應(yīng)用暴露的審計(jì)事件 (比如認(rèn)證進(jìn)入、訂單失敗)
GET/beans描述應(yīng)用程序上下文里全部的 Bean,以及它們的關(guān)系
GET/conditions就是 1.0 的 /autoconfig ,提供一份自動(dòng)配置生效的條件情況,記錄哪些自動(dòng)配置條件通過了,哪些沒通過
GET/configprops描述配置屬性(包含默認(rèn)值)如何注入Bean
GET/env獲取全部環(huán)境屬性
GET/env/{name}根據(jù)名稱獲取特定的環(huán)境屬性值
GET/flyway提供一份 Flyway 數(shù)據(jù)庫遷移信息
GET/liquidbase顯示Liquibase 數(shù)據(jù)庫遷移的纖細(xì)信息
GET/health報(bào)告應(yīng)用程序的健康指標(biāo),這些值由 HealthIndicator 的實(shí)現(xiàn)類提供
GET/heapdumpdump 一份應(yīng)用的 JVM 堆信息
GET/httptrace顯示HTTP足跡,最近100個(gè)HTTP request/repsponse
GET/info獲取應(yīng)用程序的定制信息,這些信息由info打頭的屬性提供
GET/logfile返回log file中的內(nèi)容(如果 logging.file 或者 logging.path 被設(shè)置)
GET/loggers顯示和修改配置的loggers
GET/metrics報(bào)告各種應(yīng)用程序度量信息,比如內(nèi)存用量和HTTP請(qǐng)求計(jì)數(shù)
GET/metrics/{name}報(bào)告指定名稱的應(yīng)用程序度量值
GET/scheduledtasks展示應(yīng)用中的定時(shí)任務(wù)信息
GET/sessions如果我們使用了 Spring Session 展示應(yīng)用中的 HTTP sessions 信息
POST/shutdown關(guān)閉應(yīng)用程序,要求endpoints.shutdown.enabled設(shè)置為true
GET/mappings描述全部的 URI路徑,以及它們和控制器(包含Actuator端點(diǎn))的映射關(guān)系
GET/threaddump獲取線程活動(dòng)的快照
GET/prometheus以 Prometheus 服務(wù)器可以抓取的格式公開指標(biāo)。需要依賴micrometer-registry-prometheus.

下面著重講下實(shí)際項(xiàng)目用到的。

Health

health 主要用來檢查應(yīng)用的運(yùn)行狀態(tài),這是我們使用最高頻的一個(gè)監(jiān)控點(diǎn)。監(jiān)控實(shí)例的運(yùn)行狀態(tài),以及應(yīng)用不”健康“的原因,比如數(shù)據(jù)庫連接、磁盤空間不夠等。

健康信息詳情是否公開可以配置,例如:

management.endpoint.health.show-details=always
  • never 從不顯示細(xì)節(jié),默認(rèn)
  • when-authorized 詳細(xì)信息僅向授權(quán)用戶顯示??梢允褂?配置授權(quán)角色management.endpoint.health.roles。
  • always 向所有用戶顯示詳細(xì)信息。

Spring Boot 會(huì)自動(dòng)配置HealthIndicators下表中列出的內(nèi)容。您也可以通過配置啟用或禁用選定的指標(biāo)management.health.key.enabled,key如下表所示:

鑰匙姓名描述
cassandraCassandraDriverHealthIndicator檢查 Cassandra 數(shù)據(jù)庫是否已啟動(dòng)。
couchbaseCouchbaseHealthIndicator檢查 Couchbase 集群是否已啟動(dòng)。
dbDataSourceHealthIndicator檢查是否可以獲得連接DataSource。
diskspaceDiskSpaceHealthIndicator檢查磁盤空間不足。
elasticsearchElasticsearchRestHealthIndicator檢查 Elasticsearch 集群是否已啟動(dòng)。
hazelcastHazelcastHealthIndicator檢查 Hazelcast 服務(wù)器是否已啟動(dòng)。
influxdbInfluxDbHealthIndicator檢查 InfluxDB 服務(wù)器是否已啟動(dòng)。
jmsJmsHealthIndicator檢查 JMS 代理是否已啟動(dòng)。
ldapLdapHealthIndicator檢查 LDAP 服務(wù)器是否已啟動(dòng)。
mailMailHealthIndicator檢查郵件服務(wù)器是否已啟動(dòng)。
mongoMongoHealthIndicator檢查 Mongo 數(shù)據(jù)庫是否已啟動(dòng)。
neo4jNeo4jHealthIndicator檢查 Neo4j 數(shù)據(jù)庫是否已啟動(dòng)。
pingPingHealthIndicator始終以 響應(yīng)UP。
rabbitRabbitHealthIndicator檢查 Rabbit 服務(wù)器是否已啟動(dòng)。
redisRedisHealthIndicator檢查 Redis 服務(wù)器是否已啟動(dòng)。
solrSolrHealthIndicator檢查 Solr 服務(wù)器是否已啟動(dòng)。

可以在配置文件中關(guān)閉特定的健康檢查指標(biāo),比如關(guān)閉 redis 的健康檢查:

management.health.redis.enabled=false

Info

info 就是我們自己配置在配置文件中以 info 開頭的配置信息,您可以通過設(shè)置Spring 屬性來自定義info端點(diǎn)公開的數(shù)據(jù)。info.*鍵下的所有Environment屬性都會(huì)自動(dòng)公開。例如,您可以將以下設(shè)置添加到application.yaml文件中:

info:
  app:
    name: spring-boot-actuator
    version: 1.0.0
    test: test
    encoding: @project.build.sourceEncoding@
    source: @java.version@
    target: @java.version@

啟動(dòng)項(xiàng)目,訪問:http://localhost:8080/actuator/info返回部分信息如下:

{
	"app": {
		"name": "spring-boot-actuator",
		"version": "1.0.0",
		"test": "test",
		"encoding": "UTF-8",
		"source": "1.8.0_102",
		"target": "1.8.0_102"
	}
}

安全

要特別注意暴露的URL的安全性,例如,/actuator/env可以獲取當(dāng)前機(jī)器的所有環(huán)境變量,不可暴露給公網(wǎng)。

為了保證 actuator 暴露的監(jiān)控接口的安全性,需要添加安全控制的依賴spring-boot-start-security依賴,訪問應(yīng)用監(jiān)控端點(diǎn)時(shí),都需要輸入驗(yàn)證信息。

則默認(rèn)情況下使用基于表單的HTTP身份驗(yàn)證來保護(hù)端點(diǎn)。

Security 依賴,可以選擇不加,不進(jìn)行安全管理,但不建議這么做。

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

代碼如下:

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    /*
     * version1:
     * 1. 限制 '/shutdown'端點(diǎn)的訪問,只允許ACTUATOR_ADMIN訪問
     * 2. 允許外部訪問其他的端點(diǎn)
     * 3. 允許外部訪問靜態(tài)資源
     * 4. 允許外部訪問 '/'
     * 5. 其他的訪問需要被校驗(yàn)
     * version2:
     * 1. 限制所有端點(diǎn)的訪問,只允許ACTUATOR_ADMIN訪問
     * 2. 允許外部訪問靜態(tài)資源
     * 3. 允許外部訪問 '/'
     * 4. 其他的訪問需要被校驗(yàn)
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // version1
//        http
//                .authorizeRequests()
//                    .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
//                        .hasRole("ACTUATOR_ADMIN")
//                .requestMatchers(EndpointRequest.toAnyEndpoint())
//                    .permitAll()
//                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
//                    .permitAll()
//                .antMatchers("/")
//                    .permitAll()
//                .antMatchers("/**")
//                    .authenticated()
//                .and()
//                .httpBasic();

        // version2
        http
                .authorizeRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint())
                    .hasRole("ACTUATOR_ADMIN")
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                    .permitAll()
                .antMatchers("/")
                    .permitAll()
                .antMatchers("/**")
                    .authenticated()
                .and()
                .httpBasic();
    }
}

application.properties的相關(guān)配置如下:

# Spring Security Default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ACTUATOR_ADMIN

高級(jí)

自定義健康檢查

要提供自定義健康信息,您可以注冊(cè)實(shí)現(xiàn)該HealthIndicator接口的 Spring bean。您需要提供該health()方法的實(shí)現(xiàn)并返回Health響應(yīng)。Health響應(yīng)應(yīng)包含狀態(tài),并且可以選擇包含要顯示的其他詳細(xì)信息。以下代碼顯示了一個(gè)示例HealthIndicator實(shí)現(xiàn):

@Component
public class EasyAdminHealthIndicator extends AbstractHealthIndicator {
    @Override
    public void doHealthCheck(Health.Builder builder) throws Exception {
        boolean checkHealth = check();
        if (checkHealth) {
            builder.up();
        } else {
            builder.down();
        }
        builder.withDetail("code", "200")
                .withDetail("msg", "i am ok");
    }
    private boolean check() {
        return true;
    }
}

啟動(dòng)項(xiàng)目,訪問:http://localhost:8080/actuator/health返回信息如下:

{
	"status": "UP",
	"components": {
		"db": {
			"status": "UP",
			"details": {
				"database": "MySQL",
				"validationQuery": "isValid()"
			}
		},
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 332861009920,
				"free": 312464228352,
				"threshold": 10485760,
				"exists": true
			}
		},
		"easyAdmin": {         // do do do
			"status": "UP",
			"details": {
				"code": "200",
				"msg": "i am ok"
			}
		},
		"mail": {
			"status": "UP",
			"details": {
				"location": "smtp.qq.com:-1"
			}
		},
		"ping": {
			"status": "UP"
		}
	}
}

自定義metrics指標(biāo)

兩種常用指標(biāo)類型(Metric Type)

gauge, counter, summary, timer

gauge: 可增可減計(jì)數(shù)器,反應(yīng)某值當(dāng)前一刻狀態(tài)。比如稱重傳感器的當(dāng)前重量,溫度傳感器的當(dāng)前溫度。

方式一:

Gauge.builder("gn.temperature.gauge", new AtomicInteger(37), AtomicInteger::get)

方式二:

registry.gauge("gn.temperature.gauge", Tags.of("site", "SiteA", "cab", "cab01"), new AtomicInteger(37));

counter:只增不減計(jì)數(shù)器,是Gauge的一個(gè)特例。適用于只有服務(wù)器重啟時(shí)候才會(huì)重置的計(jì)數(shù)場(chǎng)景。比如"用戶訪問次數(shù)",某接口失敗次數(shù)"等等。API 使用方式類似。

Counter counter = Counter.builder("gn.beat.counter")
  .tags("site", "SiteA", "function", "foo")
  .description("for request errors")
  .register(registry);
counter.increment();

融入到系統(tǒng)的方式

方式一: 業(yè)務(wù)系統(tǒng)埋點(diǎn)

@Component
public class SampleBean {
    private final Counter counter;
    private final List<String> list = new CopyOnWriteArrayList<>();;
    public SampleBean(MeterRegistry registry) {
        this.counter = registry.counter("laker.counter");
         registry.gauge("laker.size", Tags.empty(), this.list.size());
    }
    public void handleMessage(String message) {
        this.counter.increment();
        list.add(message);
    }
    public void handleRemoveMessage(String message) {
        list.remove(message);
    }
}

方式二:MeterBinder

SpringBoot中提供了MeterBinder接口用于申明與注冊(cè)meterRegistry。自定義Metrics只需要實(shí)現(xiàn)MeterBinder接口,Spring會(huì)自動(dòng)發(fā)現(xiàn)并完成后續(xù)的雜活。

@Bean
public class MyMetrics implements MeterBinder {
   @Override
   public void bindTo(MeterRegistry meterRegistry) {
    //此處添加相關(guān)指標(biāo)
    meterRegistry.gauge("laker.gauge", Tags.of("site", "SiteA"), new AtomicInteger(37));
   }
}

在瀏覽器訪問http://localhost:8080/actuator/metrics/laker.counter

結(jié)果如下

{
    "name": "laker.counter",
    "description": null,
    "baseUnit": null,
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 9.0
        }
    ],
    "availableTags": []
}

其他使用情況可參考:MetricsAutoConfiguration.java

PID PORT過程監(jiān)控

  • ApplicationPidFileWriter創(chuàng)建一個(gè)包含應(yīng)用程序 PID 的文件(默認(rèn)情況下,在應(yīng)用程序目錄中,文件名為application.pid)。
  • WebServerPortFileWriter創(chuàng)建一個(gè)文件(或多個(gè)文件),其中包含正在運(yùn)行的 Web 服務(wù)器的端口(默認(rèn)情況下,在應(yīng)用程序目錄中,文件名為application.port)。

默認(rèn)情況下,這些編寫器未激活:

@SpringBootApplication
public class LakerMapApplication {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(LakerMapApplication.class);
        springApplication.addListeners(new ApplicationPidFileWriter(), new WebServerPortFileWriter("./laker.port"));
        springApplication.run(args);
    }
}

配置文件:

spring: 
  pid:
    # 寫入pid的文件
    file: ./laker.pid
    # 當(dāng)無法寫入pid文件的時(shí)候,是否拋出異常
    fail-on-write-error: false

自定義管理端點(diǎn)路徑

management.endpoints.web.base-path=/manage

將端點(diǎn)從/actuator/{id}更改為/manage/{id}(例如,/manage/info)。

如果要將端點(diǎn)映射到不同的路徑,可以使用該management.endpoints.web.path-mapping屬性。

以下示例重新映射/actuator/health/healthcheck

management.endpoints.web.base-path=/
management.endpoints.web.path-mapping.health=healthcheck

自定義管理服務(wù)器端口

management.server.port=8081
management.server.address=127.0.0.1

暴露數(shù)據(jù)給Prometheus

因?yàn)楸┞秲?nèi)部信息的特性,Actuator 也可以和一些外部的應(yīng)用監(jiān)控系統(tǒng)整合(Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic等)。這些監(jiān)控系統(tǒng)提供了出色的儀表板,圖形,分析和警報(bào),可幫助你通過一個(gè)統(tǒng)一友好的界面,監(jiān)視和管理你的應(yīng)用程序。

添加依賴

為了讓Spring Boot 應(yīng)用和Prometheus 集成,你需要增加micrometer-registry-prometheus依賴。

<!-- Micrometer Prometheus registry  -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

添加上述依賴項(xiàng)之后,Spring Boot 將會(huì)自動(dòng)配置 PrometheusMeterRegistryCollectorRegistry來以Prometheus 可以抓取的格式收集和導(dǎo)出指標(biāo)數(shù)據(jù)。

所有的相關(guān)數(shù)據(jù),都會(huì)在Actuator 的 /prometheus端點(diǎn)暴露出來。Prometheus 可以抓取該端點(diǎn)以定期獲取度量標(biāo)準(zhǔn)數(shù)據(jù)。

添加micrometer-registry-prometheus依賴后,我們?cè)L問http://localhost:8080/actuator/prometheus地址。

參考:

https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/production-ready-features.html

https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html

https://segmentfault.com/a/1190000021611510

到此這篇關(guān)于教你集成Spring Boot Actuator監(jiān)控開發(fā)腳手架的文章就介紹到這了,更多相關(guān)Spring Boot Actuator監(jiān)控腳手架內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論