SpringCloud中的Consul詳解
1. Consul 簡介

Consul是 HashiCorp 公司推出的開源工具,用于實現(xiàn)分布式系統(tǒng)的服務(wù)發(fā)現(xiàn)與配置。與其它分布式服 務(wù)注冊與發(fā)現(xiàn)的方案,Consul 的方案更“一站式”,內(nèi)置了服務(wù)注冊與發(fā)現(xiàn)框 架、分布一致性協(xié)議實 現(xiàn)、健康檢查、Key/Value 存儲、多數(shù)據(jù)中心方案,不再需要依賴其它工具(比如 ZooKeeper 等)。 使用起來也較為簡單。Consul 使用 Go 語言編寫,因此具有天然可移植性(支持Linux、windows和 Mac OS X);安裝包僅包含一個可執(zhí)行文件,方便部署,與 Docker 等輕量級容器可無縫配合。
2. 專業(yè)名詞
- agent
組成 consul 集群的每個成員上都要運行一個 agent,可以通過 consul agent 命令來啟動。agent可以運行在 server 狀態(tài)或者 client 狀態(tài)。自然的, 運行在 server 狀態(tài)的節(jié)點被稱為 server 節(jié)點,運行在 client 狀態(tài)的節(jié)點被稱 為 client 節(jié)點。
- server 節(jié)點
負(fù)責(zé)組成 cluster 的復(fù)雜工作(選舉server 自行選舉一個 leader、狀態(tài)維 護(hù)、轉(zhuǎn)發(fā)請求到 leader),以及 consul 提供的服務(wù)(響應(yīng)RPC 請求),以及存放和復(fù)制數(shù)據(jù)。考慮到容錯和可用性,一般部署 3 ~ 5 個比較合適。
- client 節(jié)點
負(fù)責(zé)轉(zhuǎn)發(fā)所有的 RPC 到 server 節(jié)點。本身無狀態(tài),且輕量級,因此,可以部署大量的client 節(jié)點。
- 數(shù)據(jù)中心
雖然數(shù)據(jù)中心的定義似乎很明顯,但仍有一些細(xì)微的細(xì)節(jié)必須考慮。我們 將一個數(shù)據(jù)中心定義為一個私有、低延遲和高帶寬的網(wǎng)絡(luò)環(huán)境。這不包括通過公共互聯(lián)網(wǎng)的通信,但是為了我們的目的,單個EC2 (aws云主機)區(qū)域內(nèi)的多個可用區(qū)域?qū)⒈灰暈閱蝹€數(shù)據(jù)中心的一部分。
3. Consul 的優(yōu)勢
- 使用 Raft 算法來保證一致性, 比復(fù)雜的 Paxos 算法更直接. 相比較而言, zookeeper 采用的是 Paxos, 而 etcd 使用的則是 Raft。
- 支持多數(shù)據(jù)中心,內(nèi)外網(wǎng)的服務(wù)采用不同的端口進(jìn)行監(jiān)聽。 多數(shù)據(jù)中心集群可以避免單數(shù)據(jù)中心 的單點故障,而其部署則需要考慮網(wǎng)絡(luò)延遲, 分片等情況等。 zookeeper 和 etcd 均不提供多數(shù)據(jù)中 心功能的支持。
- 支持健康檢查。 etcd 不提供此功能。
- 支持 http 和 dns 協(xié)議接口。 zookeeper 的集成較為復(fù)雜, etcd 只支持 http 協(xié)議。 官方提供 web 管理界面, etcd 無此功能。
綜合比較, Consul 作為服務(wù)注冊和配置管理的新星, 比較值得關(guān)注和研究。
4. 特性
- 服務(wù)發(fā)現(xiàn)
- 健康檢查
- Key/Value 存儲
- 多數(shù)據(jù)中心
5. Consul與Eureka的區(qū)別
1.一致性 Consul強一致性(CP)
- 服務(wù)注冊相比Eureka會稍慢一些。因為Consul的raft協(xié)議要求必須過半數(shù)的節(jié)點都寫入成功才認(rèn) 為注冊成功
- Leader掛掉時,重新選舉期間整個consul不可用。保證了強一致性但犧牲了可用性。
2.Eureka保證高可用和最終一致性(AP)
- 服務(wù)注冊相對要快,因為不需要等注冊信息replicate到其他節(jié)點,也不保證注冊信息是否 replicate成功
- 當(dāng)數(shù)據(jù)出現(xiàn)不一致時,雖然A, B上的注冊信息不完全相同,但每個Eureka節(jié)點依然能夠正常對外提 供服務(wù),這會出現(xiàn)查詢服務(wù)信息時如果請求A查不到,但請求B就能查到。如此保證了可用性但犧牲了一致性。
6. Consul 安裝
6.1 docker-compose安裝
以dev模式啟動 且 設(shè)置client=0.0.0.0為所有ip都可以連接此服務(wù)
version: '2'
services:
consul-container:
image: consul
container_name: consul-dev
environment:
- CONSUL_BIND_INTERFACE=eth0
ports:
- "8500:8500"
volumes:
- "./config:/consul/config/"
- "./data/:/consul/data/"
command: agent -dev -client=0.0.0.0服務(wù)啟動成功后,通過瀏覽器訪問localhost:8500,顯示如下頁面即安裝成功。

7. Quick Start
7.1 啟動consul服務(wù)
本文使用的是docker-compose方式管理consul服務(wù),直接啟動即可
7.2 創(chuàng)建客戶端-provider
7.2.1 引入依賴坐標(biāo)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!--actuator用于心跳檢查--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
7.2.2 配置application.yml
server:
port: ${port:8082}
spring:
application:
name: provider
cloud:
consul:
#consul服務(wù)地址
host: 127.0.0.1
#consul服務(wù)端口
port: 8500
discovery:
#是否注冊
register: true
#實例ID
# instance-id: ${spring.application.name}-${server.port}
instance-id: ${spring.application.name}:${random.value}
#服務(wù)實例名稱
service-name: ${spring.application.name}
#服務(wù)實例端口
port: ${server.port}
#健康檢查路徑
healthCheckPath: /actuator/health
#健康檢查時間間隔
healthCheckInterval: 15s
#開啟ip地址注冊
prefer-ip-address: true
#實例的請求ip
ip-address: ${spring.cloud.client.ip-address}7.2.3 添加測試方法
package com.ldx.provider.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@Autowired
private DiscoveryClient discoveryClient;
@Value("${server.port}")
private String port;
@GetMapping("products")
public String products(){
List<ServiceInstance> list = discoveryClient.getInstances("consumer");
if(list != null && list.size() > 0 ) {
ServiceInstance serviceInstance = list.get(0);
System.out.println(serviceInstance);
}
return "Hello World:" + port;
}
}7.3 創(chuàng)建客戶端-comsumer
創(chuàng)建過程和provider一樣 測試方法換一下,并且在啟動類上添加RestTemplate Bean
7.3.1 配置application.yml
server:
port: ${port:8081}
spring:
application:
name: consumer
cloud:
consul:
#consul服務(wù)地址
host: 127.0.0.1
#consul服務(wù)端口
port: 8500
discovery:
#是否注冊
register: true
#實例ID
# instance-id: ${spring.application.name}-${server.port}
instance-id: ${spring.application.name}:${random.value}
#服務(wù)實例名稱
service-name: ${spring.application.name}
#服務(wù)實例端口
port: ${server.port}
#健康檢查路徑
healthCheckPath: /actuator/health
#健康檢查時間間隔
healthCheckInterval: 15s
#開啟ip地址注冊
prefer-ip-address: true
#實例的請求ip
ip-address: ${spring.cloud.client.ip-address}
metadata:
#添加自定義元數(shù)據(jù)
my-name: zhangtieniu-consumer7.3.2 添加支持負(fù)載均衡的RestTemplate
package com.ldx.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate loadbalancedRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}7.3.3 添加測試方法
package com.ldx.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping()
public String consumer(){
return this.restTemplate.getForObject("http://provider/products", String.class);
}
}7.4 啟動
啟動了兩個 provider 和一個 consumer

瀏覽器輸入localhost:8500 查看consul控制臺,顯示服務(wù)注冊成功

測試服務(wù)調(diào)用


其中provider 輸出的 實例信息如下:
[ConsulServiceInstance@4c2b7437 instanceId = 'consumer-6cfd981c90545313155d1f43c3ed23a5', serviceId = 'consumer', host = '192.168.0.101', port = 8081, secure = false, metadata = map['my-name' -> 'zhangtieniu-consumer', 'secure' -> 'false'], uri = http://192.168.0.101:8081, healthService = HealthService{node=Node{id='3fe6ea9e-3846-ff8d-b01f-a6528caaa3fd', node='44a66c1caa9c', address='172.26.0.2', datacenter='dc1', taggedAddresses={lan=172.26.0.2, lan_ipv4=172.26.0.2, wan=172.26.0.2, wan_ipv4=172.26.0.2}, meta={consul-network-segment=}, createIndex=11, modifyIndex=13}, service=Service{id='consumer-6cfd981c90545313155d1f43c3ed23a5', service='consumer', tags=[], address='192.168.0.101', meta={my-name=zhangtieniu-consumer, secure=false}, port=8081, enableTagOverride=false, createIndex=275, modifyIndex=275}, checks=[Check{node='44a66c1caa9c', checkId='serfHealth', name='Serf Health Status', status=PASSING, notes='', output='Agent alive and reachable', serviceId='', serviceName='', serviceTags=[], createIndex=11, modifyIndex=11}, Check{node='44a66c1caa9c', checkId='service:consumer-6cfd981c90545313155d1f43c3ed23a5', name='Service 'consumer' check', status=PASSING, notes='', output='HTTP GET http://192.168.0.101:8081/actuator/health: 200 Output: {"status":"UP"}', serviceId='consumer-6cfd981c90545313155d1f43c3ed23a5', serviceName='consumer', serviceTags=[], createIndex=275, modifyIndex=278}]}]
到此這篇關(guān)于SpringCloud-Consul的文章就介紹到這了,更多相關(guān)SpringCloud Consul內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Java?redis中緩存穿透?緩存擊穿?雪崩三種現(xiàn)象以及解決方法
緩存穿透是指緩存和數(shù)據(jù)庫中都沒有的數(shù)據(jù),而用戶不斷發(fā)起請求,如發(fā)起為id為“-1”的數(shù)據(jù)或id為特別大不存在的數(shù)據(jù)。這時的用戶很可能是攻擊者,攻擊會導(dǎo)致數(shù)據(jù)庫壓力過大2022-01-01
Java實現(xiàn)學(xué)生信息管理系統(tǒng)超詳細(xì)教程
這篇文章主要介紹了一個簡單的Java學(xué)生信息管理系統(tǒng),使用ArrayList集合存儲學(xué)生對象信息,并實現(xiàn)了添加、刪除、修改和查看學(xué)生信息的功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
springboot配置mysql數(shù)據(jù)庫spring.datasource.url報錯的解決
這篇文章主要介紹了springboot配置mysql數(shù)據(jù)庫spring.datasource.url報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot登錄驗證token攔截器的實現(xiàn)
本文主要介紹了SpringBoot登錄驗證token攔截器的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Java基于logback?MessageConverter實現(xiàn)日志脫敏方案分析
本文介紹了一種日志脫敏方案,即基于logbackMessageConverter和正則匹配的方法,該方法的優(yōu)點是侵入性低,工作量少,只需修改xml配置文件,適用于老項目,感興趣的朋友跟隨小編一起看看吧2024-10-10
JAVA實現(xiàn)sm3加密簽名以及防止重復(fù)攻擊
這篇文章主要給大家介紹了關(guān)于JAVA實現(xiàn)sm3加密簽名以及防止重復(fù)攻擊的相關(guān)資料,SM3是簽名算法,和MD5一樣(對于應(yīng)用層來說),SM4是對稱加密算法,和AES一樣(對于應(yīng)用層來說),需要的朋友可以參考下2023-10-10
Mybatis中如何設(shè)置sqlSession自動提交
在MyBatis中,默認(rèn)情況下,獲取的SqlSession對象不會自動提交事務(wù),這意味著在進(jìn)行更新、刪除或插入等操作后,需要顯式調(diào)用commit方法來提交事務(wù),但是,可以在獲取SqlSession時通過將openSession方法的參數(shù)設(shè)置為true2024-09-09

