注册中心
一般具有以下功能:
注册服务
订阅服务
失败重新注册和订阅
本地缓存服务信息列表
大体过程如下:
1.服务提供者暴露服务后向注册中心注册,如果多个注册中心的话,需要分别注册到多个注册中心;注册信息包含自己主机名,端口号,服务名,其他额外参数等。本地一般用map缓存已经注册的服务,当然也可以用文件保存到本地,当网络抖动等原因重新恢复连接Zookeeper的时候,需要从缓存取出来重新注册。
2.服务消费者引用服务提供者的时候要向zookeeper发出订阅请求,订阅服务提供者。服务消费者一般会缓存服务提供者消息,这样每次发起RPC请求的时候就不用连接zookeeper,增加性能。当服务提供者发出变动的时候,能做出相应调整,更新本地缓存。
实现例子
首先需要有注册中心接口,负责注册订阅以及查找
public interface Registry {
void register(URL url) throws Exception;
void subscribe(URL url, NotifyListener listener) throws Exception;
List<URL> lookup(URL url) throws Exception;
}
目录服务,负责查询本地缓存的服务提供者信息
public interface Directory<T> {
List<Invoker<T>> list(Invocation invocation);
}
注册节点监听器,负责注册中心有变动时候做出响应
public interface StateListener {
void onChanged(StateEvent stateEvent) throws Exception;
}
zookeeper状态监听器,负责zookeeper重连时候自动恢复注册和订阅
public interface StateListener {
void onChanged(StateEvent stateEvent) throws Exception;
}
zookeeper客户端
public interface ZkClient {
void create(URL url) throws Exception;
List<String> getChildNode(String path) throws Exception;
List<String> addNodeListener(final URL url, final ChildListener listener) throws Exception;
void addStateListener(StateListener stateListener);
}
源码
https://github.com/Jdoing/example/tree/master/example-registry