在elastic job中,只实现了基于zookeeper的注册中心。类图如下:
基于Zookeeper的注册中心
基于Zookeeper的注册中心ZookeeperRegistryCenter
实现了协调分布式服务的注册中心CoordinatorRegistryCenter
,协调分布式注册中心继承了接口注册中心RegistryCenter
。
接口注册中心要求实现一些基本方法:
public interface RegistryCenter {
/**
* 初始化注册中心.
*/
void init();
/**
* 关闭注册中心.
*/
void close();
/**
* 获取注册数据.
*
* @param key 键
* @return 值
*/
String get(String key);
/**
* 获取数据是否存在.
*
* @param key 键
* @return 数据是否存在
*/
boolean isExisted(String key);
/**
* 持久化注册数据.
*
* @param key 键
* @param value 值
*/
void persist(String key, String value);
/**
* 更新注册数据.
*
* @param key 键
* @param value 值
*/
void update(String key, String value);
/**
* 删除注册数据.
*
* @param key 键
*/
void remove(String key);
/**
* 获取注册中心当前时间.
*
* @param key 用于获取时间的键
* @return 注册中心当前时间
*/
long getRegistryCenterTime(String key);
/**
* 直接获取操作注册中心的原生客户端.
* 如:Zookeeper或Redis等原生客户端.
*
* @return 注册中心的原生客户端
*/
Object getRawClient();
}
协调分布式服务注册中心在注册中心的基础上要求实现更多的方法:
public interface CoordinatorRegistryCenter extends RegistryCenter {
/**
* 直接从注册中心而非本地缓存获取数据.
*
* @param key 键
* @return 值
*/
String getDirectly(String key);
/**
* 获取子节点名称集合.
*
* @param key 键
* @return 子节点名称集合
*/
List<String> getChildrenKeys(String key);
/**
* 获取子节点数量.
*
* @param key 键
* @return 子节点数量
*/
int getNumChildren(String key);
/**
* 持久化临时注册数据.
*
* @param key 键
* @param value 值
*/
void persistEphemeral(String key, String value);
/**
* 持久化顺序注册数据.
*
* @param key 键
* @param value 值
* @return 包含10位顺序数字的znode名称
*/
String persistSequential(String key, String value);
/**
* 持久化临时顺序注册数据.
*
* @param key 键
*/
void persistEphemeralSequential(String key);
/**
* 添加本地缓存.
*
* @param cachePath 需加入缓存的路径
*/
void addCacheData(String cachePath);
/**
* 释放本地缓存.
*
* @param cachePath 需释放缓存的路径
*/
void evictCacheData(String cachePath);
/**
* 获取注册中心数据缓存对象.
*
* @param cachePath 缓存的节点路径
* @return 注册中心数据缓存对象
*/
Object getRawCache(String cachePath);
}
基于zookeeper的协调式注册中心实现了上述两个接口。该类构造方法接收一个参数:ZookeeperConfiguration,描述zookeeper的配置信息。
public final class ZookeeperConfiguration {
/**
* 连接Zookeeper服务器的列表.
* 包括IP地址和端口号.
* 多个地址用逗号分隔.
* 如: host1:2181,host2:2181
*/
private final String serverLists;
/**
* 命名空间.
*/
private final String namespace;
/**
* 等待重试的间隔时间的初始值.
* 单位毫秒.
*/
private int baseSleepTimeMilliseconds = 1000;
/**
* 等待重试的间隔时间的最大值.
* 单位毫秒.
*/
private int maxSleepTimeMilliseconds = 3000;
/**
* 最大重试次数.
*/
private int maxRetries = 3;
/**
* 会话超时时间.
* 单位毫秒.
*/
private int sessionTimeoutMilliseconds;
/**
* 连接超时时间.
* 单位毫秒.
*/
private int connectionTimeoutMilliseconds;
/**
* 连接Zookeeper的权限令牌.
* 缺省为不需要权限验证.
*/
private String digest;
}
基于Zookeeper的注册中心在初始化时利用上述的配置信息,使用apache curator框架创建zookeeper client,并完成客户端初始化。该类本身提供的各种方法基本上基于该curator客户端实现。