Spring Cloud 使用Zookeeper作为注册中心
Spring Cloud注册中心
在spring cloud体系中,有多种手段实现注册中心,例如Euerka、Consul、Zookeeper等,本篇文章主要分享使用Zookeeper作为注册中心,下面是 Spring Cloud 支持的服务发现软件以及特性对比:
Feature |
Euerka |
Consul |
Zookeeper |
Etcd |
服务健康检查 |
可配支持 |
服务状态,内存,硬盘等 |
(弱)长连接,keepalive |
连接心跳 |
多数据中心 |
—— |
支持 |
—— |
—— |
kv 存储服务 |
—— |
支持 |
支持 |
支持 |
一致性 |
—— |
raft |
paxos |
raft |
cap |
ap |
ca |
cp |
cp |
使用接口(多语言能力) |
http(sidecar) |
支持 http 和 dns |
客户端 |
http/grpc |
watch 支持 |
支持 long polling/大部分增量 |
全量/支持long polling |
支持 |
支持 long polling |
自身监控 |
metrics |
metrics |
—— |
metrics |
安全 |
—— |
acl /https |
acl |
https 支持(弱) |
spring cloud 集成 |
支持 |
支持 |
支持 |
支持 |
使用Zookeeper
增加依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <exclusions> <exclusion> // 排除内部使用的zk客户端 <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </exclusion> <exclusion> // 已废弃 <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-netflix-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> // 使用跟自己zk版本一致的客户端 <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> </dependency>
|
增加配置
1 2 3 4 5 6 7 8 9
| spring: cloud: zookeeper: connect-string: localhost:2181 discovery: prefer-ip-address: true // 优先使用IP instance-ip-address: ${address.local} // 配置zk注册IP metadata: // 自定义属性配置 property : ${value}
|
1 2 3 4 5 6 7 8 9
| @SpringBootApplication @EnableDiscoveryClient public class WebApplication {
public static void main(String[] args) throws Exception { SpringApplication.run(WebApplication.class, args); }
}
|
注册结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { "name":"name", "id":"03bd781d-ef9d-4297-8e51-e9f92c706592", "address":"ip", "port":, "sslPort":null, "payload":{ "@class":"org.springframework.cloud.zookeeper.discovery.ZookeeperInstance", "id":"application-1", "name":"name", "metadata":{ "property":"value" } } }
|