亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

spring boot的健康檢查HealthIndicators實戰(zhàn)

 更新時間:2021年10月19日 12:13:09   作者:南北雪樹  
這篇文章主要介紹了spring boot的健康檢查HealthIndicators實戰(zhàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

springboot 健康檢查HealthIndicators

想提供自定義健康信息,你可以注冊實現(xiàn)了HealthIndicator接口的Spring beans。

你需要提供一個health()方法的實現(xiàn),并返回一個Health響應(yīng)。

Health響應(yīng)需要包含一個status和可選的用于展示的詳情。

import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealth implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
} r
eturn Health.up().build();
}
}

除了Spring Boot預(yù)定義的Status類型,Health也可以返回一個代表新的系統(tǒng)狀態(tài)的自定義Status。

在這種情況下,需要提供一個HealthAggregator接口的自定義實現(xiàn),或使用management.health.status.order屬性配置默認(rèn)的實現(xiàn)。

例如,假設(shè)一個新的,代碼為FATAL的Status被用于你的一個HealthIndicator實現(xiàn)中。 為了配置嚴(yán)重程度, 你需要將下面的配

置添加到application屬性文件中:

management.health.status.order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP

如果使用HTTP訪問health端點, 你可能想要注冊自定義的status, 并使用HealthMvcEndpoint進(jìn)行映射。 例如, 你可以將

FATAL映射為HttpStatus.SERVICE_UNAVAILABLE。

springboot health indicator原理及其使用

作用

sping boot health 可以通過暴露的接口來提供系統(tǒng)及其系統(tǒng)組件是否可用。默認(rèn)通過/health來訪問。返回結(jié)果如下:

{
  "status": "UP",
  "discoveryComposite": {
    "description": "Spring Cloud Eureka Discovery Client",
    "status": "UP",
    "discoveryClient": {
      "description": "Spring Cloud Eureka Discovery Client",
      "status": "UP",
      "services": [
        "..."
      ]
    },
    "eureka": {
      "description": "Remote status from Eureka server",
      "status": "UP",
      "applications": {
        "AOMS-MOBILE": 1,
        "DATA-EXCHANGE": 1,
        "CLOUD-GATEWAY": 2,
        "AOMS": 1,
        "AOMS-AIIS": 0,
        "AOMS-EUREKA": 2
      }
    }
  },
  "diskSpace": {
    "status": "UP",
    "total": 313759301632,
    "free": 291947081728,
    "threshold": 10485760
  },
  "refreshScope": {
    "status": "UP"
  },
  "hystrix": {
    "status": "UP"
  }
}

狀態(tài)說明:

  • UNKNOWN:未知狀態(tài),映射HTTP狀態(tài)碼為503
  • UP:正常,映射HTTP狀態(tài)碼為200
  • DOWN:失敗,映射HTTP狀態(tài)碼為503
  • OUT_OF_SERVICE:不能對外提供服務(wù),但是服務(wù)正常。映射HTTP狀態(tài)碼為200

注意:UNKNOWN,DOWN,OUT_OF_SERVICE在為微服務(wù)環(huán)境下會導(dǎo)致注冊中心中的實例也為down狀態(tài),請根據(jù)具體的業(yè)務(wù)來正確使用狀態(tài)值。

自動配置的Health Indicator

自動配置的HealthIndicator主要有以下內(nèi)容:

Key Name Description
cassandra CassandraDriverHealthIndicator Checks that a Cassandra database is up.
couchbase CouchbaseHealthIndicator Checks that a Couchbase cluster is up.
datasource DataSourceHealthIndicator Checks that a connection to DataSource can be obtained.
diskspace DiskSpaceHealthIndicator Checks for low disk space.
elasticsearch ElasticsearchRestHealthIndicator Checks that an Elasticsearch cluster is up.
hazelcast HazelcastHealthIndicator Checks that a Hazelcast server is up.
influxdb InfluxDbHealthIndicator Checks that an InfluxDB server is up.
jms JmsHealthIndicator Checks that a JMS broker is up.
ldap LdapHealthIndicator Checks that an LDAP server is up.
mail MailHealthIndicator Checks that a mail server is up.
mongo MongoHealthIndicator Checks that a Mongo database is up.
neo4j Neo4jHealthIndicator Checks that a Neo4j database is up.
ping PingHealthIndicator Always responds with UP.
rabbit RabbitHealthIndicator Checks that a Rabbit server is up.
redis RedisHealthIndicator Checks that a Redis server is up.
solr SolrHealthIndicator Checks that a Solr server is up.

分組

可以通過一個別名來啟用一組指標(biāo)的訪問。配置的格式如下:

management.endpoint.health.group.<name>
//demo:
management.endpoint.health.group.mysys.include=db,redis,mail
management.endpoint.health.group.custom.exclude=rabbit

如何管理Health Indicator

開啟

可以通過management.health.key.enabled來啟用key對應(yīng)的indicator。例如:

management.health.db.enabled=true

關(guān)閉

management.health.db.enabled=false

RedisHealthIndicator源碼解析

下面,通過RedisHealthIndicator源碼來為什么可以這么寫。

代碼結(jié)構(gòu)

自動配置的health indicator有HealthIndicator和HealthIndicatorAutoConfiguration兩部分組成。

HealthIndicator所在包在org.springframework.boot.actuate,

HealthIndicatorAutoConfiguration所在包在org.springframework.boot.actuate.autoconfigure下

//RedisHealthIndicator.java
public class RedisHealthIndicator extends AbstractHealthIndicator {
	static final String VERSION = "version";
	static final String REDIS_VERSION = "redis_version";
	private final RedisConnectionFactory redisConnectionFactory;
	public RedisHealthIndicator(RedisConnectionFactory connectionFactory) {
		super("Redis health check failed");
		Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
		this.redisConnectionFactory = connectionFactory;
	}
	@Override
	protected void doHealthCheck(Health.Builder builder) throws Exception {
		RedisConnection connection = RedisConnectionUtils
				.getConnection(this.redisConnectionFactory);
		try {
			if (connection instanceof RedisClusterConnection) {
				ClusterInfo clusterInfo = ((RedisClusterConnection) connection)
						.clusterGetClusterInfo();
				builder.up().withDetail("cluster_size", clusterInfo.getClusterSize())
						.withDetail("slots_up", clusterInfo.getSlotsOk())
						.withDetail("slots_fail", clusterInfo.getSlotsFail());
			}
			else {
				Properties info = connection.info();
				builder.up().withDetail(VERSION, info.getProperty(REDIS_VERSION));
			}
		}
		finally {
			RedisConnectionUtils.releaseConnection(connection,
					this.redisConnectionFactory);
		}
	}
}

主要實現(xiàn)doHealthCheck方法來實現(xiàn)具體的判斷邏輯。注意,操作完成后在finally中釋放資源。

在父類AbstractHealthIndicator中,對doHealthCheck進(jìn)行了try catch,如果出現(xiàn)異常,則返回Down狀態(tài)。

 //AbstractHealthIndicator.java
 @Override
 public final Health health() {
  Health.Builder builder = new Health.Builder();
  try {
   doHealthCheck(builder);
  }
  catch (Exception ex) {
   if (this.logger.isWarnEnabled()) {
    String message = this.healthCheckFailedMessage.apply(ex);
    this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE,
      ex);
   }
   builder.down(ex);
  }
  return builder.build();
 }

RedisHealthIndicatorAutoConfiguration完成RedisHealthIndicator的自動配置

@Configuration
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("redis")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter({ RedisAutoConfiguration.class,
  RedisReactiveHealthIndicatorAutoConfiguration.class })
public class RedisHealthIndicatorAutoConfiguration extends
  CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {
 private final Map<String, RedisConnectionFactory> redisConnectionFactories;
 public RedisHealthIndicatorAutoConfiguration(
   Map<String, RedisConnectionFactory> redisConnectionFactories) {
  this.redisConnectionFactories = redisConnectionFactories;
 }
 @Bean
 @ConditionalOnMissingBean(name = "redisHealthIndicator")
 public HealthIndicator redisHealthIndicator() {
  return createHealthIndicator(this.redisConnectionFactories);
 }
}

重點說明ConditionalOnEnabledHealthIndicator:如果management.health..enabled為true,則生效。

CompositeHealthIndicatorConfiguration 中會通過HealthIndicatorRegistry注冊創(chuàng)建的HealthIndicator

自定義Indicator

@Component
@ConditionalOnProperty(name="spring.dfs.http.send-url")
@Slf4j
public class DfsHealthIndicator implements HealthIndicator {
    @Value("${spring.dfs.http.send-url}")
    private String dsfSendUrl;
    @Override
    public Health health() {
        log.debug("正在檢查dfs配置項...");
        log.debug("dfs 請求地址:{}",dsfSendUrl);
        Health.Builder up = Health.up().withDetail("url", dsfSendUrl);
        try {
            HttpUtils.telnet(StringUtils.getIpFromUrl(dsfSendUrl),StringUtils.getPortFromUrl(dsfSendUrl));
            return up.build();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("DFS配置項錯誤或網(wǎng)絡(luò)超時");
            return up.withException(e).build();
        }
    }
}

返回值:

{
    "dfs": {
    "status": "UP",
    "url": "10.254.131.197:8088",
    "error": "java.net.ConnectException: Connection refused (Connection refused)"
    }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot的跨域注解@CrossOrigin解析

    SpringBoot的跨域注解@CrossOrigin解析

    這篇文章主要介紹了SpringBoot的跨域注解@CrossOrigin解析,Spring Framework 4.2 GA為CORS提供了第一類支持,使您比通常的基于過濾器的解決方案更容易和更強(qiáng)大地配置它,所以springMVC的版本要在4.2或以上版本才支持@CrossOrigin,需要的朋友可以參考下
    2023-12-12
  • Spring MVC的優(yōu)點與核心接口_動力節(jié)點Java學(xué)院整理

    Spring MVC的優(yōu)點與核心接口_動力節(jié)點Java學(xué)院整理

    這篇文章主要介紹了Spring MVC的優(yōu)點與核心接口,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • 詳解SpringBoot如何實現(xiàn)多環(huán)境配置

    詳解SpringBoot如何實現(xiàn)多環(huán)境配置

    在實際的軟件開發(fā)過程中,一個應(yīng)用程序通常會有多個環(huán)境,pring?Boot?提供了一個非常靈活和強(qiáng)大的方式來管理這些環(huán)境配置,下面就跟隨小編一起學(xué)習(xí)一下吧
    2023-07-07
  • postman中實現(xiàn)傳遞@RequestBody參數(shù)

    postman中實現(xiàn)傳遞@RequestBody參數(shù)

    這篇文章主要介紹了postman中實現(xiàn)傳遞@RequestBody參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Maven setting配置鏡像倉庫的方法步驟

    Maven setting配置鏡像倉庫的方法步驟

    這篇文章主要介紹了Maven setting配置鏡像倉庫的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12
  • Springboot中的自定義攔截器及原理詳解

    Springboot中的自定義攔截器及原理詳解

    這篇文章主要介紹了Springboot中的自定義攔截器及原理詳解,攔截器主要是用于在用戶請求控制中,對于請求識別,鑒權(quán),以及區(qū)分資源是否可以被目標(biāo)方法調(diào)用的安全機(jī)制,需要的朋友可以參考下
    2023-12-12
  • 100-200之間所有素數(shù)求和程序代碼(二個版本)

    100-200之間所有素數(shù)求和程序代碼(二個版本)

    寫一個求100-200之間素數(shù),并求和的程序,大家參考使用吧
    2013-11-11
  • SpringBoot之自定義Banner詳解

    SpringBoot之自定義Banner詳解

    這篇文章主要介紹了SpringBoot之自定義Banner詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • java防盜鏈在報表中的應(yīng)用實例(推薦)

    java防盜鏈在報表中的應(yīng)用實例(推薦)

    下面小編就為大家?guī)硪黄猨ava防盜鏈在報表中的應(yīng)用實例(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-09-09
  • Java中正則表達(dá)式的使用和詳解(上)

    Java中正則表達(dá)式的使用和詳解(上)

    這篇文章主要介紹了Java中正則表達(dá)式的使用和詳解,包括匹配驗證驗證email是否正確,在字符串中查詢字符或者字符串的代碼實例,需要的朋友可以參考下
    2017-04-04

最新評論