1.curator介绍
curator是Netflix开源的一个zookeeper客户端,比zookeeper自带的客户端使用起来容易得多
2.依赖
org.apache.curator:curator-framework:2.7.1
org.apache.curator:curator-recipes:2.7.1
org.apache.curator:curator-x-discovery:2.7.1
其中 curator-x-discovery是用于服务发现的专用包
如果只是测试可以加上
org.apache.curator:curator-test:2.7.1
通过这个包可以模拟zookeeper 不需要真实的zookeeper服务也可以运行
3.具体实现
创建客户端
CuratorFramework client= CuratorFrameworkFactory.newClient(“localhost:2181”,newExponentialBackoffRetry(1000, 3));
client.start();
4.创建服务发现
private static final String PATH=”/discovery/example”; ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build();
serviceDiscovery.start();
其中PATH为服务配置所在目录
5.服务变更通知
final ServiceCache
cache=serviceDiscovery.serviceCacheBuilder().name(“s1”).build();
cache.addListener(new ServiceCacheListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
//TODOAuto-generated method stub
}
@Override
public void cacheChanged() {
System.out.println(“changed:”+cache.getInstances().size());
}
});
cache.start();
其中“s1”为服务名称,服务配置就在这个目录下面 。当“s1”服务配置发送变化时cacheChanged方法将会被调用
6.生成可用服务实例
UriSpec uriSpec=new UriSpec(“{scheme}://foo.com:{port}”);
ServiceInstance thisInstance = ServiceInstance.builder()
.name(serviceName)
.payload(newInstanceDetails(description))
.port((int)(65535 * Math.random()))// in a real application, you’d use a common port
.uriSpec(uriSpec)
.build();
7.添加服务实例
JsonInstanceSerializer serializer=new JsonInstanceSerializer(InstanceDetails.class);
ServiceDiscovery serviceDiscovery= ServiceDiscoveryBuilder.builder(InstanceDetails.class)
.client(client)
.basePath(path)
.serializer(serializer)
.thisInstance(thisInstance)
.build();
serviceDiscovery.start();
InstanceDetails 是自定义配置信息 添加服务实例代码实际使用中在服务提供方代码中,这样当服务挂掉,zookeeper中的相应配置节点也会消失 并通知服务的调用方
8.查询服务配置
try
{
CollectionserviceNames=serviceDiscovery.queryForNames();
System.out.println(serviceNames.size() +” type(s)”);
for( StringserviceName:serviceNames)
{
Collection>instances=serviceDiscovery.queryForInstances(serviceName);
System.out.println(serviceName);
for( ServiceInstanceinstance:instances)
{
outputInstance(instance);
}
}
}
finally
{
CloseableUtils.closeQuietly(serviceDiscovery);
}