2016-06-15 1 views
2

큐레이터 treeCache을 사용할 때 어떻게 캐시를 준비 할 수 있습니까?큐레이터 treeCache를 사용할 때 어떻게 캐시를 준비 할 수 있습니까?

cache.start() 이후에 즉시 getCurrentData으로 전화하면 null이 반환되므로 캐시를 어떻게 준비 할 수 있습니까?, 누군가 내게 예제를 줄 수 있습니까? NodeState 그것이를 반환 LIVE 때 getCurrentChildren의 코드에서 감사

client = CuratorFrameworkFactory.builder() 
      .connectString(connectionString) 
      .retryPolicy(new ExponentialBackoffRetry(zkConnectionTimeoutMs, 3)) 
      .sessionTimeoutMs(zkSessionTimeoutMs) 
      .build(); 
client.start(); 

cache = new TreeCache(client, rootPath); 
cache.start(); 
ChildData child = cache.getCurrentData(rootPath); // child is null 
Thread.sleep(50); // must sleep for a while 
child = cache.getCurrentData(rootPath); // child is ok 

답변

1

Treecache에 대한 수신기를 추가하고 INITIALIZED 이벤트를 수신 할 수 있습니다.

Semaphore sem = new Semaphore(0); 
    client = CuratorFrameworkFactory.builder() 
           .connectString(connectionString) 
           .retryPolicy(new ExponentialBackoffRetry(zkConnectionTimeoutMs, 3)) 
           .sessionTimeoutMs(zkSessionTimeoutMs) 
           .build(); 
     client.start(); 

     cache = new TreeCache(client, rootPath); 
        cache.start(); 

     TreeCacheListener listener = new TreeCacheListener() { 

            @Override 
            public void childEvent(CuratorFramework client, TreeCacheEvent event) 
              throws Exception { 
             switch (event.getType()) { 
             case INITIALIZED: { 

              sem.release(); 

             } 

            } 

           }; 
     cache.getListenable().addListener(listener); 
     sem.acquire(); 
child = cache.getCurrentData(rootPath); 
+0

누구나 이보다 더 좋은 해결책을 찾았습니까? –

1

public Map<String, ChildData> getCurrentChildren(String fullPath) 
{ 
    TreeNode node = find(fullPath); 
    if (node == null || node.nodeState.get() != NodeState.LIVE) 
    { 
     return null; 
    } 
    ConcurrentMap<String, TreeNode> map = node.children.get(); 
    Map<String, ChildData> result; 
    if (map == null) 
    { 
     result = ImmutableMap.of(); 
    } 
    else 
    { 
     ImmutableMap.Builder<String, ChildData> builder = ImmutableMap.builder(); 
     for (Map.Entry<String, TreeNode> entry : map.entrySet()) 
     { 
      TreeNode childNode = entry.getValue(); 
      ChildData childData = new ChildData(childNode.path, childNode.stat.get(), childNode.data.get()); 
      // Double-check liveness after retreiving data. 
      if (childNode.nodeState.get() == NodeState.LIVE) 
      { 
       builder.put(entry.getKey(), childData); 
      } 
     } 
     result = builder.build(); 
    } 

    // Double-check liveness after retreiving children. 
    return node.nodeState.get() == NodeState.LIVE ? result : null; 
} 

당신은 NodeState가 보류 또는 DEAD 또는 존재하지 않는 경우, 그것은 null를 돌려주는 것을 볼 수 있습니다 지도 인스턴스. 따라서 반환 값이 null이 아니면 캐시가 준비됩니다.