我爱java系列---【springboot项目集成zookeeper作为注册中心】

1.引入maven依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
            <version>2.1.1.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeeper</groupId>
                    <artifactId>zookeeper</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <!-- 与服务器安装的Zookeeper版本相同 -->
            <version>3.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

上面的依赖放到<dependencies>标签中,下面的放到<dependencies>标签同级目录中

<!--SpringCloud所有依赖管理的坐标-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.在springboot启动类上加上注解:@EnableDiscoveryClient

3.在yml中加上配置

spring:
  application:
    #本地测试
    name: dblocalhost
    #测试服务器
    #name: db201
  cloud:
    zookeeper:
      connect-string: 190.7.18.193:2181
      #connect-string: localhost:2181
      discovery:
        enabled: true
        register: true
        instance-host: ${spring.cloud.client.ip-address}  //自动获取启动服务的ip注册到zk注册中心
        #instance-host: 180.8.16.47   //也可以写死,建议写上面的那种用法
        root: /sms  //注册到zk之后的根节点的名称

相关推荐