springboot 使用zookeeper实现服务注册和发现

一、目录结构

此项目实例是使用多模块maven,并配合springboot进行构建
结构如下图所示


image.png
二、每个maven的配置

这里是父maven的配置

<?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>
    <packaging>pom</packaging>
    <modules>
        <module>order</module>
        <module>product</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/>
    </parent>


    <groupId>com.example</groupId>
    <artifactId>springboot_zookeeper</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_zookeeper</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.12</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

order服务下的maven

<?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">
    <parent>
        <artifactId>springboot_zookeeper</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order</artifactId>


</project>

product服务下的maven

<?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">
    <parent>
        <artifactId>springboot_zookeeper</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>product</artifactId>


</project>
三、product模块

此模块下的Application代码

package com.example.product;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Properties;

@SpringBootApplication
@RestController
public class Application {


    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);

    }

    @RequestMapping(value = "/product/id",method = RequestMethod.GET)
    public String  get(HttpServletRequest request){
        return "访问 product  服务端口:"+ request.getLocalPort();
    }

    @Bean
    public Register register(){
        Register register = new Register();
        register.register11(getAddressAndPort());
        return register;
    }


    private String getAddressAndPort(){
        try {
            Properties properties = new Properties();
            InputStream stream = Application.class.getClassLoader().getResourceAsStream("application.properties");
            properties.load(stream);

            Object port = properties.get("server.port");
            return "127.0.0.1:" + port;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }
}

使用Register实现服务的注册

package com.example.product;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class Register {

    private static final String SERVER_PATH = "/product";

    private static final String ZK_ADDRESS = "94.*.*.51:4180";

    private static final int ZK_TIMEOUT = 20000;

    public void register11(String address){
        try{
            ZooKeeper zooKeeper = new ZooKeeper(ZK_ADDRESS,ZK_TIMEOUT, WatchEvent ->{

            });
            Stat stat = zooKeeper.exists(SERVER_PATH,false);
            if(stat==null){
                zooKeeper.create(SERVER_PATH,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            String path = address;
            //创建短暂的可排序的子节点
            zooKeeper.create(SERVER_PATH+"/instance",path.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

此模块中对应的application.properties配置

server.port=8086
四、order模块

此模块下的Application代码

package com.example.order;



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@SpringBootApplication
@RestController
public class Application {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ZookListener listener;

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    public ZookListener zookListener(){
        ZookListener listener = new ZookListener();
        listener.init();
        return listener;
    }

    @RequestMapping(value = "/order/id",method = RequestMethod.GET)
    public String get(){
        //从zookeeper中获取调用的ip
        String path = listener.getPath();
        if(path == null){
            return "对不起,产品暂时停止服务!";
        }
        return restTemplate.getForObject("http://"+listener.getPath()+"/product/id",String.class);
    }


    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

此模块下使用ZookListener类实现获取zookeeper的节点列表,也可以监听zookeeper里面的节点变化

package com.example.order;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;


public class ZookListener {

    private static final String SERVER_PATH="/product";

    private static final String ZK_ADDRESS="94.*.*.51:4180";

    private static final int ZK_TIMEOUT = 20000;

    private ZooKeeper zooKeeper;

    private List<String> paths = new LinkedList<>();

    public void init(){
        try{
            zooKeeper = new ZooKeeper(ZK_ADDRESS,ZK_TIMEOUT,(WatchEvent)->{
                getChilds();
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getChilds(){
        List<String> ips = new LinkedList<>();
        try{
            //添加监听
            List<String> childs = this.zooKeeper.getChildren(SERVER_PATH,true);
            for(String child:childs){
                byte[] obj = zooKeeper.getData(SERVER_PATH+"/"+child,false,null);
                String path = new String(obj,"utf-8");
                ips.add(path);
            }
            this.paths = ips;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getPath(){
        if(paths.isEmpty()){
            return null;
        }
        int index = new Random().nextInt(paths.size());
        return paths.get(index);
    }
}

此模块中的application.properties

server.port = 8080
四、测试

分别启动两个模块的application,如下图


image.png

访问浏览器地址http://127.0.0.1:8080/order/id,如下显示

image.png

查看zookeeper中的节点值,如下图显示


image.png
停止服务

当我们停止了product模块的时候,访问浏览器,会提示服务停止,如下图


image.png

再看看zookeeper中的节点,过了几秒后,就会自动删除了


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270