当前位置:   article > 正文

SpringBoot ,zookeeper 服务的注册与发现_将springboot集群注册到zk上,使网关服务可获取所有服务节点状态

将springboot集群注册到zk上,使网关服务可获取所有服务节点状态

本文主要讲zookeeper如何注册服务并使用这些服务。简单流程是使用springboot开发简单的restapi.并把api注册到zookeeper。最后在客户端连接到zookeeper调用api并把结果返回到客户端。

  • springboot开发restapi
  • 注册服务到zookeeper
  • 发现服务

springboot开发restapi

搭建springboot开发环境

新建一个maven工程,并引入spring boot的jar包。pom配置是:

<parent>  
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-parent</artifactId>  
      <version>1.3.3.RELEASE</version>  
  </parent> 
  • 1
  • 2
  • 3
  • 4
  • 5
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
  • 1
  • 2
  • 3
  • 4

写一个测试的api

package demo.msa.sample;

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

@RestController
@SpringBootApplication(scanBasePackages="demo.msa")
public class SampleApplication {

    @RequestMapping(name="HelloService",method=RequestMethod.GET,path="/hello")
    public String hello(){
        return "hello";
    }

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

启动后访问效果如下:
这里写图片描述
端口配置是在application.properties
这里写图片描述

注册服务到zookeeper

zookeeper服务器搭建

zookeeper本地搭建,网上有很多教程,这里不在赘述。说一下服务注册的原理
zookeeper的结构是基于znode的树状结构。根节点是‘/’,我们可以在根节点下扩展任意节点。
这里写图片描述
这里写图片描述

下面开始具体的开发:
(1)新建两个项目,msa-framework和msa-sample-api。
(2)在msa-framework定义服务注册表接口

package demo.msa.framework.registry;

public interface ServiceRegistry {
   

    /**
     * 注册服务信息
     * @param serviceName 服务名称
     * @param serviceAddress 服务地址
     */
    void register(String serviceName,String serviceAddress);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

打包,并引入到msa-sample-api工程

<dependency>
        <groupId>demo.msa</groupId>
        <artifactId>msa-framework</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

(3)在msa-sample-api项目中创建一个ServiceRegistry的实现类。实现注册接口。

package demo.msa.frame.registry;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
imp
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/851672
推荐阅读
相关标签
  

闽ICP备14008679号