服務注冊與發現


隨着業務的發展,用戶量日益上升,單一的系統越來越復雜,越來越龐大,單純的提升服務器性能始終有見頂的一天,我們可以通過分布式技術,例如:服務器集群,水平業務划分,應用分解,系統分流,微服務架構等方式來解決系統性能問題和復雜業務問題。在微服務架構或分布式環境下,服務注冊與發現不可或缺。

在微服務架構下,一個應用被拆解為若干個微服務,組成一個分布式應用,各種服務間互相調用。另一方面,出於性能或可用性的考慮,一個微服務常常會部署多份,組成一個集群。如何自動確定系統中有哪些服務、一個服務有哪些實例、這些服務的地址等信息等是個問題,服務注冊與發現組件用於解決該問題。

服務注冊與發現組件有zookeeper、etcd、consul、eureka等。這里介紹consul。

在生產環境中,特別是在分布式環境或微服務架構下,服務數量眾多。此時往往需要做到服務注冊、發現、配置的自動化,以能在服務增加或減少時自動調整配置,避免人工配置。Consul + Consul-Template + Registrator (+ Nginx + Docker )是個完美搭配,以下介紹這三者。

1、Consul

以下以 Consul v1.3.0 為例

1.1、What

Consul是HashiCorp公司推出的開源工具,用於實現分布式系統的服務發現與配置。它具備以下特性:

  • 服務發現:Consul提供了通過DNS或者HTTP接口的方式來注冊服務和發現服務。
  • 健康檢測:Consul的Client提供了健康檢查的機制,在服務發現時可以忽略有故障的服務,從而避免流量被轉發到有故障的服務上。
  • Key/Value存儲:應用程序可根據自己的需要使用Consul提供的Key/Value存儲。 Consul提供了簡單易用的HTTP接口,結合其他工具可以實現動態配置、功能標記、領導選舉等功能。
  • 多數據中心:Consul支持開箱即用的多數據中心. 這意味着用戶不需要擔心需要建立額外的抽象層讓業務擴展到多個區域。

Consul采用Go開發而成,使用Raft算法(比Zookeeper等采用的復雜的Paxos算法更簡單)來保證數據一致性。

與其他分布式服務注冊與發現的方案相比,Consul的方案更“一站式”:內置了服務注冊與發現框架、分布一致性協議實現、健康檢查、Key/Value存儲、多數據中心方案,不再需要依賴其他工具(比如ZooKeeper等),此外,提供了HTTP Rest API、DNS API等,易用性強。

1.2、Consul架構及角色

Consul架構如上圖所示,相關名詞有Consul Agent、Server、Client。

萬變不離其宗,作為一個分布式組件,Consul中的節點也是C/S架構的,具有Client和Server兩種類型或稱角色;不管哪種角色,每個Consul節點都是一個Consul Agent;若干個Consul Agent組成了一個Consul Cluster。

  • Consul Cluster:所有Consul Agent組成的整體,包括若干個Consul Client和若干Consul Server節點。
  • Consul Server:用於維護Consul Cluster的狀態信息。 官方建議是:至少要運行3個或者3個以上的Consul Server。 多個server之中需要選舉一個leader,該選舉過程Consul基於Raft協議實現。多個Server節點上的Consul數據信息保持強一致性。在局域網內與本地客戶端通訊,通過廣域網與其他數據中心通訊。
  • Consul Client:一個Client是一個轉發所有RPC到Server的代理。只維護自身的狀態,用來處理健康檢查、將HTTP和DNS接口請求轉發到服務節點等。Client不會參與leader選舉因此不會成為leader

一個Consul Cluster中必須至少一個Server,可以沒有Client。

(ps:這里的Agent與通常理解中的 'Agent' 含義不一樣,后者通常指本地代理,負責轉發本地調用者的讀寫請求到Server並返回給調用者。如Zookeeper的Client(某種語言的SDK)相當於Zookeeper Server的 ‘Agent’ 。故Consul Client更像是通常理解中的 ‘Agent’ ,而Consul Agent更像是Zookeeper Server & Client) 

 

1.3、安裝與運行

1.3.1、安裝

Consul用Go實現,因此具有天然可移植性(支持 Linux、windows 和macOS)。Consul安裝非常簡單,安裝包僅包含一個可執行文件,只需要下載對應系統的軟件包並解壓后就可使用(官方下載地址:https://www.consul.io/downloads.html

驗證安裝: $ consul ,類似輸出如下:

 1 Usage: consul [--version] [--help] <command> [<args>]
 2 
 3 Available commands are:
 4     agent          Runs a Consul agent
 5     catalog        Interact with the catalog
 6     connect        Interact with Consul Connect
 7     event          Fire a new event
 8     exec           Executes a command on Consul nodes
 9     force-leave    Forces a member of the cluster to enter the "left" state
10     info           Provides debugging information for operators.
11     intention      Interact with Connect service intentions
12     join           Tell Consul agent to join cluster
13     keygen         Generates a new encryption key
14     keyring        Manages gossip layer encryption keys
15     kv             Interact with the key-value store
16     leave          Gracefully leaves the Consul cluster and shuts down
17     lock           Execute a command holding a lock
18     maint          Controls node or service maintenance mode
19     members        Lists the members of a Consul cluster
20     monitor        Stream logs from a Consul agent
21     operator       Provides cluster-level tools for Consul operators
22     reload         Triggers the agent to reload configuration files
23     rtt            Estimates network round trip time between nodes
24     services       Interact with services
25     snapshot       Saves, restores and inspects snapshots of Consul server state
26     validate       Validate config files/directories
27     version        Prints the Consul version
28     watch          Watch for changes in Consul
View Code 

1.3.2、運行Consul Agent

(更多詳細命令可以通過加 -h 查看,如 consul -h 、 consul agent -h )

啟動:所謂啟動就是運行一個Consul Agent實例,可以作為Server或Client角色運行。

運行一個Consul Server Agent: consul agent -data-dir /consul/data -bind=$localPublicIP -node=node_$localPublicIP -client=0.0.0.0 -ui -retry-join=$joinedConsulServerIP -server -bootstrap-expect 1 

運行一個Consul Client Agent: consul agent -data-dir /consul/data -bind=$localPublicIP -node=node_$localPublicIP -client=0.0.0.0 -ui -retry-join=$joinedConsulServerIP 

主要參數說明:(兩個必須參數,更多關於參數含義見官方文檔:https://www.consul.io/docs/agent/options.html

 -data-dir :必須,用於指定狀態數據的存儲目錄

 -bind :必須,Sets the bind address for cluster communication,指定用於集群內節點間通信的IP,默認是0.0.0.0,但機子有多個IP時必須顯示指定一個。只能是IP,若跨數據中心則須是公網IP

 -node :指定本Agent在集群中的名稱,須唯一。默認采用機器的hostname,建議采用IP

 -client :Sets the address to bind for client access. This includes RPC, DNS, HTTP and HTTPS (if configured)。相當於白名單,允許哪些來源的IP可以訪問本Agent,可以用來控制是否允許遠程訪問,默認為127.0.0.1,指定為0.0.0.0則允許所有來源的IP訪問。

 -ui :Enables the built-in static web UI server,在server、client上均可啟用,但看到的東西一樣(因為看到的是同一個集群的信息)。默認訪問地址:http://${IP}/8500

 -retry-join :啟動時將本Agent加入到指定IP所代表的Agent所在的集群,該IP地址可以為一個Client或Server的地址。(也可用 -join 參數,但顯然此帶重試的參數更好)。問題:join到多個server addr以防一個unreachable?

 -server :以Server模式運行Agent,沒有該參數則以Client模式運行

 -bootstrap-expect :僅用於server模式的agent。用於指定一個datacenter中有多少個server,這些server上此值需要一樣。Consul會等這些Server都啟動后才會開始可用。

 -dev :創建一個開發環境下的server節點。該參數配置下,不會有任何持久化操作即不會有任何數據寫入到磁盤,因此此模式不能用於生產環境,僅用於測試。

Consul Agent啟動后會默認監聽5個端口:

8300: replication、leader farwarding的端口
8301: lan cossip的端口
8302: wan gossip的端口
8500: web ui界面的端口
8600: 使用dns協議查看節點信息的端口

停止:Ctrl + V

  

1.4、使用

與其他服務注冊與發現組件相比,Consul還提供了HTTP API和DNS API,使得非常易用。

這里列舉各功能下的幾個常用API使用示例,供日后快速查閱。

1.4.1、endpoints

consul的主要接口是RESTful HTTP API,該API可以用來增刪查改nodes、services、checks、configguration等。所有的endpoints主要分為以下類別:

kv - Key/Value存儲
agent - Agent控制
catalog - 管理nodes和services
health - 管理健康監測
session - Session操作
acl - ACL創建和管理
event - 用戶Events
status - Consul系統狀態

各模塊具體內容可參閱:https://my.oschina.net/FrankXin/blog/1524853,如:

/v1/catalog/register : Registers a new node, service, or check
/v1/catalog/deregister : Deregisters a node, service, or check
/v1/catalog/datacenters : Lists known datacenters
/v1/catalog/nodes : Lists nodes in a given DC
/v1/catalog/services : Lists services in a given DC
/v1/catalog/service/<service> : Lists the nodes in a given service
/v1/catalog/node/<node> : Lists the services provided by a node

 

1.4.2、查看集群信息

通過CommandLine查看集群信息示例:

$ consul members     # 列出集群Agent成員
$ consul info |grep leader  # 列出集群Leader列表
$ consul catalog services  # 列出集群中的服務列表

members命令的輸出是基於gossip協議的且其內容是最終一致的。也就是說,在任何時候在本地代理看到的內容可能與當前服務器中的狀態並不是絕對一致的。若需要強一致性的信息,可用如下的HTTP API。

通過HTTP API查看集群信息示例:

# 集群server成員
$ curl 127.0.0.1:8500/v1/status/peers

# 集群Raft leader
$ curl 127.0.0.1:8500/v1/status/leader

# 注冊的所有服務
$ curl 127.0.0.1:8500/v1/catalog/services
$ curl 127.0.0.1:8500/v1/catalog/service/$servicename

# 集群節點詳細信息
$ curl 127.0.0.1:8500/v1/catalog/nodes
$ curl 127.0.0.1:8500/v1/catalog/node/$nodename

 

1.4.3、服務注冊、刪除、發現

更多可參考官方文檔:https://www.consul.io/api/agent/service.html

(1)服務注冊:Consul支持兩種服務注冊方式,推薦后者

法一:通過配置文件注冊:寫好.json配置文件並在啟動agent時通過 -config-dir 指定該配置文件,文件內容示例如下(可不全指定各字段):

 1     {
 2         "service": {
 3             "id":"xx_ss_manage_service",
 4             "name": "ss_manage_service",
 5             "tags": ["sensestudy,backend,java"],
 6             "address": "10.5.6.47",
 7             "port": 8081,
 8             "checks": [ //會周期性檢查服務健康,對於HTTP返回2xx則認為健康
 9                 {
10                     "http": "http://10.5.6.47:8081",
11                     "interval": "10s"
12                 },//可以多個
13                 {
14                     "tcp": "10.9.10.173:8081",
15                     "interval": "10s"   
16                 }
17             ]
18         }
19     }
View Code

服務會被注冊到使用該配置文件的Agent上。

法二:通過HTTP API注冊。具體而言,可通過本地agent(/v1/agent/service/register,此時服務信息里可不用指定agent node等信息),也可通過catalog注冊(/v1/catalog/register,需要提供node、address等更多信息)

 curl -X PUT -d '{"name":"sensestudy_manage_server_java","tags":["java"],"port":8081,"checks":[{"tcp":"localhost:8081","interval":"10s"}]}' http://$agentHost:8500/v1/agent/service/register 

注:用PUT方法,PUT的值為上面配置文件里service的值服務會被注冊到http鏈接中agentHost所對應的Agent上

注:

  • 多個同name的service可以注冊到同一個agnet上,但其service id須不同;不同agnet上也可以有同name的service,其service id也可以相同。可知,agnet + service id才是整個集群中唯一的。
  • 若注冊時不指定service的IP則會默認采用所注冊到的agent的IP;若不指定service id則默認采用service name。正因為如此,若注冊時不指定IP和ID則同一個node上沒法注冊多個同名的服務。
  • 若一個Agent掛了,則該Agent及注冊到其下的service會被從cluster中移除。

(2)服務刪除:以HTTP API為例,刪除時是刪除指定Agent上的一個或若干服務

 curl -X PUT $scheme://$agentHost:8500/v1/agent/service/deregister/$servicename :刪除指定Agent上的指定服務

以上述命令為基礎,刪除本地Agent上的所有服務: curl http://localhost:8500/v1/agent/services?pretty | jq -r "to_entries|map(\"\(.key)\")|.[]" | xargs -I {} curl -X PUT http://localhost:8500/v1/agent/service/deregister/{} 

(3)服務發現:以HTTP API為例,與服務注冊類似,可以查某個agent下的服務,也可以通過catalog查集群中的服務。

 curl $scheme://$agentHost:8500/v1/catalog/services :查集群中的所有服務,在任意一個agent上得到的結果均一樣

 curl $scheme://$agentHost:8500/v1/catalog/service/$servicename :查集群中的某個服務,在任意一個agent上得到的結果均一樣

 curl $scheme://$agentHost:8500/v1/agent/services :獲取指定Agent上的所有服務

 curl $scheme://$agentHost:8500/v1/agent/service/$servicename :獲取指定Agent上的某個服務

注:

  • url最后加 pretty 參數可以格式化展示json結果,如: curl -s http://localhost:8500/v1/agent/services?pretty ,也可借助其他工具如: curl -s http://localhost:8500/v1/agent/services | python -m json.tool 
  • 注冊服務時若未設置某些字段如adress,則查詢時對於上述后兩個接口也不會有該字段值(為空)、而對於上述前兩個接口則adress會為所在Agent的adress。
  • 根據Agent啟動時-client的配置,有可能上述命令執行失敗

1.4.4、健康檢查

參閱:https://www.consul.io/docs/agent/checks.html

1.4.5、鍵值存儲

 參閱:https://www.cnblogs.com/java-zhao/p/5381892.html

1.5、Consul Docker

官網:https://hub.docker.com/_/consul/

“ Consul should always be run with --net=host in Docker because Consul's consensus and gossip protocols are sensitive to delays and packet loss

consul用於服務注冊,由於應用通過查詢注冊到consul上的服務來與服務連接,而服務通常通過本地Agent來注冊到consul上(注冊時通常不指定服務地址,從而服務的地址為所注冊到的agent的地址)。故docker里consul Agent的地址需要是其他機子能訪問到的,通過--net=host達到該目的。

示例:(查看Dockerfile可知該Consul Image的data-dir默認為/consul/data且有個匿名卷)

Server Agent:

docker run -d --net=host --restart=always --name $consulContainerName  consul agent -node=node_$localPublicIP  -bind=$localPublicIP  -client=0.0.0.0 -ui -retry-join=$joinedConsulServerIP -server -bootstrap-expect 1

Client Agent: docker run -d --net=host --restart=always --name $consulContainerName consul agent -node=node_$localPublicIP -bind=$localPublicIP -client=0.0.0.0 -ui -retry-join=$joinedConsulServerIP 

 

2、Consul-Template

下載地址:https://releases.hashicorp.com/consul-template/ (下載后即可使用)

Consul-Template用於根據模板配置文件生成真實配置文件。它會監控Consul上服務的變化,並在變化時自動根據模板文件生成新的文件(如nginx配置文件),此外還可以在生成文件后執行用戶指定的命令。

模板示例:以下是一個nginx配置文件模板

log_format  myLogFormat  '$remote_addr - $remote_user [$time_local] "$request" '
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$proxy_add_x_forwarded_for" '
                         'upstream:"$upstream_addr" upstreamResponseTime:$upstream_response_time ';


client_max_body_size 100m;

upstream httpServer {
  least_conn;
  {{range service "ss_manage_service"}}server {{.Address}}:{{.Port}} max_fails=3 fail_timeout=60 weight=1;
  {{else}}server 127.0.0.1:65535; # force a 502{{end}}
}

server {
  listen 80 default_server;

  access_log  /var/log/nginx/access.log  myLogFormat;
  
  location / {
    proxy_pass $scheme://httpServer;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}
View Code

命令示例: consul-template -consul localhost:8500 -retry 30s -template /tmp/zsmtest/nginx.conf.consultemplate:/tmp/zsmtest/nginx.conf:' nginx -s reload && echo generate new config file ' ,服務加入或離開時根據模板生成新的配置文件。

 -consul :指定consul地址

 -retry :consul不用時重試間隔

 -template :指定模板文件位置、生成的文件的位置、生成文件后執行的命令。可以指定多個-template以根據多個模板生成多個文件

更多使用指南見:https://book-consul-guide.vnzmi.com/11_consul_template.html

 

3、Registrator

Registrator用於自動發現其所在宿主機上運行的Docker container中的服務,並將服務注冊到服務注冊組件(如Consul、Zookeeper、etcd等)。當某個服務掛了,Registrator會自動將之deregister。

官方文檔:http://gliderlabs.github.io/registrator/latest/user/services/

Registrator Docker:https://hub.docker.com/r/gliderlabs/registrator/

以下以Registrator + Consul為例。這里Registrator版本為v7

3.1、原理

Registrator以容器方式運行,其啟動后會自動獲取宿主機上的Docker container列表 並 將有顯式指定 宿主機到容器端口映射( -p $publish_port:$expose_port 或 -P )的容器 作為服務注冊到Consul。

  • 若一個容器內有多個運行程序且都做了端口映射則會有多個服務被注冊到consul。
  • 會忽略沒有映射宿主機端口的容器,如--net=host的container,要想該容器不被忽略,可以在docker啟動時加入-p參數。

3.2、運行

3.2.1、示例

啟動命令示例: docker run -d --net=host --restart=always --name $registratorContainerName -v /var/run/docker.sock:/tmp/docker.sock gliderlabs/registrator -ip=$localPublicIP consul://localhost:8500 

 -ip :可選。指定被Registrator注冊到Consul上的service的ip。若不指定此參數則采用 -consul 參數的IP值。

被Registrator注冊到Consul上的service的ip為該值、端口為service所在容器的publish port(可以通過啟動時給registrator加 -internal參數使之用expose port)

由於一個service是要被其他service訪問的,故通常需要將此 -ip 設為非環回地址: -ip=<external ip of my local machine>

-consul :可選。指定service注冊到哪個Agent上,默認是127.0.0.1。實際部署時每個Consul Agent所在主機都要運行一個Registrator,故此值為默認即可

更多啟動參數及其默認值:

-cleanup=false: Remove dangling services
-deregister="always": Deregister exited services "always" or "on-success"
-internal=false: Use internal ports instead of published ones
-ip="": IP for ports mapped to the host
-resync=0: Frequency with which services are resynchronized
-retry-attempts=0: Max retry attempts to establish a connection with the backend. Use -1 for infinite retries
-retry-interval=2000: Interval (in millisecond) between retry-attempts.
-tags="": Append tags for all registered services
-ttl=0: TTL for services (default is no expiry)
-ttl-refresh=0: Frequency with which service TTLs are refreshed
View Code

defalut service name、id、address:被Registrator注冊到Consul上的服務的命名、ID、地址等值如下:

default service name:<base(container-image)>[-<exposed-port> if >1 ports]

default service ID:<hostname>:<container-name>:<exposed-port>[:udp if udp],這里hostname是指宿主機的

default IP and Port:前者 -ip 的值,如果為配置則用consul地址值中的ip;后者為$publish_port(若啟動Registrator時指定了-internal參數則為$expose_port)

3.2.2、配置

可以配置service name、tag、helth check等。

方法:在啟動docker服務時傳入環境變量或標簽,registrator會使用該變量來命名服務或進行健康檢查等。如 SERVICE_x_NAME ,x is the internal exposed port,可以不指定x,如SERVICE_NAME,但一個容器內有多個監聽端口時需要指定端口x。

示例

-e SERVICE_3306_NAME=ss_mysql_service # service name
-e SERVICE_3306_TAGS=sensestudy,backend,mysql # service tag
-e SERVICE_3306_CHECK_TCP=true # health check

更多配置參閱:http://gliderlabs.github.io/registrator/latest/user/services/

更多健康檢查配置參閱:http://gliderlabs.github.io/registrator/latest/user/backends/#consul

 

4、SpringCloud項目中使用Consul

4.1、 服務注冊

在SpringCloud(SpringBoot)項目中只需要少量配置就可以將項目自動注冊到Consul。

1、引入依賴:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

2、配置啟用Consul:

spring:
cloud: consul: enabled:
true host: localhost port: 8500 discovery: # serviceName: ${spring.application.name} #if not configured, use application in default tags: sensestudy,coursecenter healthCheckInterval: 15s fail-fast: false prefer-ip-address: true # health-check-path: ${server.servlet.context-path}/actuator/health

4.2、服務方法的定義和實現

api定義:

@RequestMapping("/api/v1")
public interface CourseApi {

    @GetMapping("/course")
    public BaseResp<CourseEntity> getCourseEntity(@RequestParam("courseId") String courseId);
}

api實現:

@RestController
public class ContrseController implements CourseApi {
    @Autowired
    private CourseService courseService;

    @Override
    public BaseResp<CourseEntity> getCourseEntity(String courseId) {
        CourseEntity courseEntity = courseService.getByCourseId(courseId);
        return BaseResp.generateSuccess(courseEntity);
    }
}

api client(也可以與api定義合二為一):

@FeignClient(value = "sensestudy-coursecenter", fallback = CourseFeignFallback.class)//通過fallback指定服務調用時的熔斷機制,另一種為通過FallBackFactory指定
public interface CourseFeignClient extends CourseApi { } 



//fallback style
@Component
public class CourseFeignFallback implements CourseFeignClient {
    @SuppressWarnings("unchecked")
    @Override
    public BaseResp<CourseEntity> getCourseEntity(String courseId) {
        return BaseResp.DEFAULT_FALLBACK_RESP;
    }
}

//FallbackFactory style
@Component
public class CourseFeignFallback implements FallbackFactory<CourseFeignClient> {
    @Override
    public CourseFeignClient create(Throwable throwable) {
        String msg = throwable == null ? "" : throwable.getMessage();
        if (!StringUtils.isEmpty(msg)) {
            log.error(msg);
        }
        return new CourseFeignClient() {
            @SuppressWarnings("unchecked")
            @Override
            public BaseResp<CourseEntity> getCourseEntity(String courseId) {
                return BaseResp.DEFAULT_FALLBACK_RESP;
            }

        };
    }

}
View Code

 

4.3、發現

服務發現借助於Feign Client。

1、依賴及配置:與注冊時的一樣,只不過需加個feign依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、在項目main方法上啟用FeignClient: @EnableFeignClients(basePackages = "xxx") 

3、Feign調用的代碼示例:

@RestController
class TestController {
    @Autowired
    private CourseFeignClient courseFeignClient;

    @GetMapping("/api/course")
    public BaseResp<CourseEntity> test() {
        return courseFeignClient.getCourseEntity("");
    }
}

注:默認情況下,引入api client后,服務提供方的請求映射在服務消費方也會生效,導致混淆或沖突,可以通過配置避免:

@Configuration
@ConditionalOnClass({ Feign.class })
public class FeignConfiguration {// 解決@FeignClient中的@RequestMapping也被服務調用方加載的問題:@FeignClient中的@RequestMapping也被

    @Bean
    public WebMvcRegistrations feignWebRegistrations() {
        return new WebMvcRegistrations() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new FeignRequestMappingHandlerMapping();
            }
        };
    }

    private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        @Override
        protected boolean isHandler(Class<?> beanType) {
            return super.isHandler(beanType) && !AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
        }
    }
}
FeignConfiguration

詳情可參閱:https://cloud.tencent.com/developer/article/1072494https://juejin.im/entry/5b20a2c25188257d6c047d2dhttps://my.oschina.net/u/1758970/blog/1798279

4、 配置啟用熔斷機制(可選): feign.hystrix.enabled=true ,Feign的fallback是通過Hystrix實現的,故該配置為true時fallback才能生效。

 

4.3、健康檢查

可借助actuator對應用進行監控,包括health、info、metrics等

引入如下依賴即可:

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

可以進行進一步配置:

spring:
management: #actuator config endpoints: web: exposure: include:
"*"

 注意:默認情況下,對一個項目健康檢查時,如果項目中引入了Spring的MySQL、Redis、MongoDB等組件(即引入Spring的相關包)則會同時檢查項目中相關組件的健康狀態,只要有一個相關組件不健康,則認為該項目也不健康。當然,可以設置不同時檢查相關組件,如management.health.redis.enabled=false。這是個大坑

 

5、參考資料

https://www.hi-linux.com/posts/6132.html

閱讀推薦:http://blog.didispace.com/consul-service-discovery-exp/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM