springCloud集成zookeper

Easter79
• 阅读 492

最近梳理springboot相关知识。看到分布式锁,其中有一种是使用zookeeper实现的,就学习一下zookeeper。本来是使用springboot和zookeeper集成的,但是试了半天,好像不行。pom文件一直冲突。无奈,参考  https://start.spring.io/ ,生成了一个小的demo,发现该demo是使用springcloud,遂弃之springboot,使用springcloud,其中的原因我猜测可能是zookeeper是一个组件,属于springcloud体系。

下面是zookeeper官网对zookeeper的介绍

ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications. Each time they are implemented there is a lot of work that goes into fixing the bugs and race conditions that are inevitable. Because of the difficulty of implementing these kinds of services, applications initially usually skimp on them ,which make them brittle in the presence of change and difficult to manage. Even when done correctly, different implementations of these services lead to management complexity when the applications are deployed.

zookeeper是被适用于分手不是应用中的。springboot是一个单体的微服务,多个单体的微服务构成分布式服务。而springcloud是一个服务治理的集成者。

——————————分割线———————————————

springCloud集成zookeeper 

1,创建一个maven工程;

2:,引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <!-- 提供zookeeper整合的包 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 热部署工具 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

说明:注意引入的依赖之间是否冲突。

2,配置文件 application.properties

#系统中用到的参数配置  编码格式
com.interview.question=springboot有哪些配置的注解
logging.level.root=INFO
logging.file=D:/logs/hello.log
server.port=8081
spring.application.name=info     ——————————————必须有该属性配置,否则启动时报空指针异常

配置文件

#spring.cloud.zookeeper.connectString=127.0.0.1:2181
3spring.cloud.zookeeper.discovery.instanceHost=127.0.0.1
#spring.cloud.zookeeper.discovery.instancePort=${server.port}

## 启用zookeeper作为配置中心
spring.cloud.zookeeper.config.enabled = true

## 配置根路径
spring.cloud.zookeeper.config.root = config

## 配置默认上下文
spring.cloud.zookeeper.config.defaultContext = zook

## 配置profile分隔符
spring.cloud.zookeeper.config.profileSeparator = -

3:,启动类

package zookeper;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
*
* 项目名称:zookeper
* 类名称:App
* 类描述:
* 创建人:john
* 创建时间:2018年7月31日 下午3:36:01
* 修改人:john
* 修改时间:2018年7月31日 下午3:36:01
* 修改备注:
* @version
*
*/
@SpringBootApplication
@EnableDiscoveryClient
public class ZookApp {
   public static void main(String[] args){
       SpringApplication.run(ZookApp.class, args);
       System.out.println("hello springcloud");
   }
}

4,controller 

package zookeper.controller;

import java.util.List;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * 项目名称:zookeper 类名称:ZookController 类描述: 创建人:john 创建时间:2018年7月31日 下午3:51:56
 * 修改人:john 修改时间:2018年7月31日 下午3:51:56 修改备注:
 * 
 * @version
 *
 */
@RestController
@RequestMapping("/zook")
public class ZookController {
    @Autowired
    private DiscoveryClient client;
    @Autowired
    private Environment environment;

    public String getZook() {
        return "";
    }

    @RequestMapping("/getServices")
    public String discoveryClent() {
        List<String> serviceList = client.getServices();
        System.out.println("注册服务的数量>>>>>>>>>>>>>>>>>" + serviceList.size());
        for (String service : serviceList) {
            System.out.println("注册的服务>>>>>>" + service);
        }
        return "info";
    }

    @GetMapping("/env")
    public String test() {
        String[] profiles = environment.getActiveProfiles();
        System.out.println("profiles>>>>>>>" + profiles.length);
        for (String item : profiles) {
            System.out.println("item>>>>>>>>>>>>>>>" + item);
        }

        String name = environment.getProperty("url");
        System.out.println(name);

        return "Hello," + name;
    }
}

5,验证 

浏览器验证

springCloud集成zookeper

elipse打印

springCloud集成zookeper

6,添加操作zookeeper的客户端  CuratorFramework(直接注入即可)

package zookeper.controller;

import java.util.List;
import org.springframework.core.env.Environment;
import org.apache.curator.framework.CuratorFramework;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * 项目名称:zookeper 类名称:ZookController 类描述: 创建人:john 创建时间:2018年7月31日 下午3:51:56
 * 修改人:john 修改时间:2018年7月31日 下午3:51:56 修改备注:
 * 
 * @version
 *
 */
@RestController
@RequestMapping("/zook")
public class ZookController {
    @Autowired
    private DiscoveryClient client;
    @Autowired
    private Environment environment;
    @Autowired
    private CuratorFramework curatorFramework;

    public String getZook() {
        return "";
    }

    @RequestMapping("/getServices")
    public String discoveryClent() {
        List<String> serviceList = client.getServices();
        List<ServiceInstance> list=client.getInstances("info");
         //获取实例化的服务
        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0 ) {
            sb.append(list.get(0).getUri()+",");
            System.out.println(">>>>>>>>>>>>>>>>"+list.get(0).isSecure());
        }
        System.out.println("sb>>>>>"+sb);
        System.out.println("注册服务的数量>>>>>>>>>>>>>>>>>" + serviceList.size());
        for (String service : serviceList) {
            System.out.println("注册的服务>>>>>>" + service);
        }
        return "info";
    }

    @GetMapping("/env")
    public String test() {
        String[] profiles = environment.getActiveProfiles();
        System.out.println("profiles>>>>>>>" + profiles.length);
        for (String item : profiles) {
            System.out.println("item>>>>>>>>>>>>>>>" + item);
        }
        
        String name = environment.getProperty("url");
        
        try {
            List <String> listChildren=curatorFramework.getChildren().forPath("/config/zook");
            for(String child:listChildren ){
                System.out.println("child>>>>>>>"+child);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println(name);

        return "Hello," + name;
    }
}

springCloud集成zookeper

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Souleigh ✨ Souleigh ✨
2年前
前端性能优化 - 雅虎军规
无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k