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

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

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

集成

引入依賴

在項目的pom.xml中增加以下依賴

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

配置文件

application.yml

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

訪問驗證

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

{
    "status": "UP"
}

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

到這里就集成完成了哈。

端點 Endpoints

Actuator默認把所有訪問點暴露給JMX,但處于安全原因,只有healthinfo會暴露給Web。

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

management:
  endpoints:
    web:
      exposure:
        # 包含所有端點使用 "*",注意有引號
        include: info, health, beans, env, metrics

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

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

下面著重講下實際項目用到的。

Health

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

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

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

Spring Boot 會自動配置HealthIndicators下表中列出的內容。您也可以通過配置啟用或禁用選定的指標management.health.key.enabled,key如下表所示:

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

可以在配置文件中關閉特定的健康檢查指標,比如關閉 redis 的健康檢查:

management.health.redis.enabled=false

Info

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

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

啟動項目,訪問: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可以獲取當前機器的所有環(huán)境變量,不可暴露給公網(wǎng)。

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

則默認情況下使用基于表單的HTTP身份驗證來保護端點。

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

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

代碼如下:

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

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

    @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的相關配置如下:

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

高級

自定義健康檢查

要提供自定義健康信息,您可以注冊實現(xiàn)該HealthIndicator接口的 Spring bean。您需要提供該health()方法的實現(xiàn)并返回Health響應。Health響應應包含狀態(tài),并且可以選擇包含要顯示的其他詳細信息。以下代碼顯示了一個示例HealthIndicator實現(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;
    }
}

啟動項目,訪問: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指標

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

gauge, counter, summary, timer

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

方式一:

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:只增不減計數(shù)器,是Gauge的一個特例。適用于只有服務器重啟時候才會重置的計數(shù)場景。比如"用戶訪問次數(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è)務系統(tǒng)埋點

@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接口用于申明與注冊meterRegistry。自定義Metrics只需要實現(xiàn)MeterBinder接口,Spring會自動發(fā)現(xiàn)并完成后續(xù)的雜活。

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

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

結果如下

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

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

PID PORT過程監(jiān)控

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

默認情況下,這些編寫器未激活:

@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
    # 當無法寫入pid文件的時候,是否拋出異常
    fail-on-write-error: false

自定義管理端點路徑

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

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

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

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

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

自定義管理服務器端口

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

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

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

添加依賴

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

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

添加上述依賴項之后,Spring Boot 將會自動配置 PrometheusMeterRegistryCollectorRegistry來以Prometheus 可以抓取的格式收集和導出指標數(shù)據(jù)。

所有的相關數(shù)據(jù),都會在Actuator 的 /prometheus端點暴露出來。Prometheus 可以抓取該端點以定期獲取度量標準數(shù)據(jù)。

添加micrometer-registry-prometheus依賴后,我們訪問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

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

相關文章

最新評論