最近在学习zookeeper,作为一个分布式协调服务,它的用途挺多,服务注册与发现、分布式锁、集群选举、配置中心等。今天我先通过一个demo实现zookeeper的服务注册与发现功能
思路
- 将产品服务的信息注册到zookeeper的节点上
- 然后获取到节点上的信息并存储起来(本文存到List)
- Watcher机制监控List里数据的变化并更新数据 (假如产品服务2挂了通过监听机制将其移出)
-
利用轮询或者hash等算法去获取List里的数据供订单服务调用(负载均衡)
注册服务
获取到zookeeper的实例并创建根节点和子节点,子节点为临时顺序节点,用于保存服务对应的ip
package com.ooliuyue.product.zk;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
/**
* @Auther: ly
* @Date: 2019/4/19 11:53
*/
public class ServiceRegister {
private static final String BASE_SERVICE = "/service";
private static final String SERVICE_NAME = "/product";
public static void register(String address,int port) {
/**
* 在zk创建根节点path,在根节点下创建临时子节点用于存放服务ip和端口
*/
try {
String path = BASE_SERVICE + SERVICE_NAME;
ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,(watchedEvent) -> {});
System.out.println(zooKeeper);
Thread.sleep(2000);
Stat exists = zooKeeper.exists(BASE_SERVICE + SERVICE_NAME, false);
//先判断服务根路径是否存在
if (exists == null){
zooKeeper.create(BASE_SERVICE + SERVICE_NAME,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
//将服务的ip和端口作为临时带序号的子节点
String server_path = address+":"+port;
zooKeeper.create(path + "/child",server_path.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("product服务注册成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
容器初始化的时候调用register(),给zk的子节点设置值(服务的url)
package com.ooliuyue.product.listen;
import com.ooliuyue.product.zk.ServiceRegister;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.InetAddress;
import java.util.Properties;
/**
* @Auther: ly
* @Date: 2019/4/19 10:43
*/
public class InitListener implements ServletContextListener {
@Override
//容器初始化的时候会调用
public void contextInitialized(ServletContextEvent sce) {
Properties properties = new Properties();
try {
properties.load(InitListener.class.getClassLoader().getResourceAsStream("application.properties"));
//获得IP
String hostAddress = InetAddress.getLocalHost().getHostAddress();
//获得端口
int port = Integer.valueOf(properties.getProperty("server.port"));
ServiceRegister.register(hostAddress,port);
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
启动服务,进行测试,前提需要启动ZooKeeper
package com.ooliuyue.product.controller;
import com.ooliuyue.product.pojo.Product;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* @Auther: ly
* @Date: 2019/4/19 09:52
*/
@RequestMapping("/product")
@RestController
public class ProductController {
@RequestMapping("/get/{id}")
public Object getProduct(HttpServletRequest request, @PathVariable("id") String id){
int localPort = request.getLocalPort();
return new Product(id,"productName:" + localPort);
}
}
两个产品服务启动成功
通过工具查看节点
服务发现
获取zk节点上保存的服务信息并保存到一个List中,watcher机制来监控List中数据的变化
package com.ooliuyue.order.listener;
import com.ooliuyue.order.utils.LoadBalance;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.List;
/**
* @Auther: ly
* @Date: 2019/4/19 16:26
*/
public class InitListener implements ServletContextListener {
private static final String BASE_SERVICE = "/service";
private static final String SERVICE_NAME = "/product";
private ZooKeeper zooKeeper;
private void init(){
try {
//连接zk,获得列表信息
//watcher机制:监控获取到的服务列表的变化
zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,(watchedEvent) -> {
if (watchedEvent.getType() == Watcher.Event.EventType.NodeChildrenChanged
&& watchedEvent.getPath().equals(BASE_SERVICE+SERVICE_NAME)) {
System.out.println("***注册到zk的服务信息发生变化***");
updateServerList();
}
});
//第一次连接的时候要返回的列表
updateServerList();
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateServerList() {
List list = new ArrayList<>();
try {
List children = zooKeeper.getChildren(BASE_SERVICE + SERVICE_NAME,true);
for(String subNode : children) {
byte[] data = zooKeeper.getData(BASE_SERVICE + SERVICE_NAME + "/" + subNode, false, null);
String host = new String(data,"utf-8");
list.add(host);
}
//将获取的服务端口和IP保存List中
LoadBalance.SERVICE_LIST = list;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
init();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
通过实现一个随机算法获取到产品服务,供订单服务调用(相当于负载)
package com.ooliuyue.order.utils;
import java.util.List;
/**
* @Auther: ly
* @Date: 2019/4/22 14:00
*/
public abstract class LoadBalance {
public volatile static List SERVICE_LIST;
public abstract String chooseServiceHost();
}
package com.ooliuyue.order.utils;
import org.springframework.util.CollectionUtils;
import java.util.Random;
/**
* @Auther: ly
* @Date: 2019/4/22 14:02
*/
//实现了一个随机的算法(随机获取订单服务)
public class RandomLoadBalance extends LoadBalance {
@Override
public String chooseServiceHost() {
String result = "";
if (!CollectionUtils.isEmpty(SERVICE_LIST)) {
int nextInt = new Random().nextInt(SERVICE_LIST.size());
result = SERVICE_LIST.get(nextInt);
}
return result;
}
}
测试调用结果
package com.ooliuyue.order.controller;
import com.ooliuyue.order.pojo.Order;
import com.ooliuyue.order.utils.LoadBalance;
import com.ooliuyue.order.utils.RandomLoadBalance;
import com.ooliuyue.product.pojo.Product;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* @Auther: ly
* @Date: 2019/4/19 10:02
*/
@RequestMapping("/order")
@RestController
public class OrderController {
@Resource
private RestTemplate restTemplate;
private LoadBalance loadBalance = new RandomLoadBalance();
@RequestMapping("/get/{id}")
public Object getOrder(HttpServletRequest request, @PathVariable("id") String id){
//随机获取host
String host = loadBalance.chooseServiceHost();
Product product = restTemplate.getForObject("http://" + host + "/product/get/1", Product.class);
return new Order(id,"ordername",product);
}
}
发起多次请求,会发现随机调用其中一个服务
Watcher机制
删除List中一个服务的信息