赞
踩
本文主要讲zookeeper如何注册服务并使用这些服务。简单流程是使用springboot开发简单的restapi.并把api注册到zookeeper。最后在客户端连接到zookeeper调用api并把结果返回到客户端。
新建一个maven工程,并引入spring boot的jar包。pom配置是:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
写一个测试的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);
}
}
启动后访问效果如下:
端口配置是在application.properties
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);
}
打包,并引入到msa-sample-api工程
<dependency>
<groupId>demo.msa</groupId>
<artifactId>msa-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
(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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。