微服务架构 | 服务注册发现中心 -[springcloud 整合 zookeeper]
@
依赖
<!-- SpringBoot整合zookeeper客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--排除后重新引入 zookeeper 的目的是保证版本和服务器上的版本一致-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--项目引入的版本和服务器上不一致时,可能导致启动失败-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
配置
#8004表示注册到zookeeper服务器的支付服务提供者端口号
server:
port: 8080
#服务别名----注册zookeeper到注册中心名称
spring:
application:
name: servicename
cloud:
zookeeper:
connect-string: zookeeper地址
启动类
重点是 @EnableDiscoveryClient 注解,此注解通用与各种注册中心
@SpringBootApplication
@EnableDiscoveryClient
public class ZookeeperServiceApplication{
public static void main(String[] args) {
SpringApplication.run(ZookeeperServiceApplication.class,args);
}
}
验证
简易安装 zookeeper 流程
1 下载包 https://zookeeper.apache.org/
2 解压缩
tar -zxvf apache-zookeeper-3.7.1-bin.tar.gz
3 增加环境变量
vim /etc/profile
# zookeeper
export ZOOKEEPER_HOME=/opt/apache-zookeeper-3.7.1-bin
export PATH=$PATH:${ZOOKEEPER_HOME}/bin
source /etc/profile
4 改配置
vim /opt/apache-zookeeper-3.7.1-bin/conf/zoo.cfg
# 设置一个单位时间,其他时间的设置都是n倍的此时间
tickTime=2000
# 节点初始化时间,节点连接到主节点并完成同步的时间
initLimit=10
# 节点同步时间,主从节点通信的时间
syncLimit=5
# 数据/日志存放路径(zookeeper的核心是一个文件系统)
dataDir=/opt/zookeeper
dataLogDir=/opt/zookeeper/logs
# 客户端端口
clientPort=2181
# 客户端最大连接数
#maxClientCnxns=60
启动 zookeeper server
./zkServer.sh start
启动时,需要确认防火墙放行相关端口
查看状态
./zkServer.sh status
启动服务(springcloud)
查看服务注册状态
进入 zkClient 命令行
./zkCli.sh
ls -R /services
get /services/payment-service-zookeeper-1/a5fdd27b-ba88-4949-9ea7-78a18f1a498e
{
"name":"payment-service-zookeeper-1",
"id":"a5fdd27b-ba88-4949-9ea7-78a18f1a498e",
"address":"MSI-DEUS",
"port":8004,
"sslPort":null,
"payload":{
"@class":"org.springframework.cloud.zookeeper.discovery.ZookeeperInstance",
"id":"application-1",
"name":"payment-service-zookeeper-1",
"metadata":{
}
},
"registrationTimeUTC":1657093753525,
"serviceType":"DYNAMIC",
"uriSpec":{
"parts":[
{
"value":"scheme",
"variable":true
},
{
"value":"://",
"variable":false
},
{
"value":"address",
"variable":true
},
{
"value":":",
"variable":false
},
{
"value":"port",
"variable":true
}
]
}
}
传送门:
微服务架构 | 组件目录