码迷,mamicode.com
首页 > 其他好文 > 详细

zookeeper持有者类

时间:2017-02-09 21:49:27      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:oid   java   except   getc   private   final   super   rri   超时   

 1 import org.apache.curator.RetryPolicy;
 2 import org.apache.curator.framework.CuratorFramework;
 3 import org.apache.curator.framework.CuratorFrameworkFactory;
 4 import org.apache.curator.framework.imps.CuratorFrameworkState;
 5 import org.apache.curator.retry.ExponentialBackoffRetry;
 6 import org.slf4j.Logger;
 7 import org.slf4j.LoggerFactory;
 8 
 9 import java.io.Closeable;
10 import java.io.IOException;
11 
12 /**
13  * zookeeper连接持有者
14  *
15  * @author
16  * @version V1.0
17  * @modify by user: $author$ $date$
18  * @modify by reason:{方法名}:{原因}
19  */
20 public class ZookeeperHolder implements Closeable {
21     // /日志
22     private static final Logger LOG = LoggerFactory.getLogger(ZookeeperHolder.class);
23     // zk超时时间
24     private static final int SESSION_TIME = 30 * 1000;
25     //出错尝试次数
26     private static final int RETRY_TIMES = 3;
27     private CuratorFramework client;
28     private String zkUrl = null;
29 
30     public ZookeeperHolder(String zkUrl) {
31         this.zkUrl = zkUrl;
32         client = initClient(zkUrl);
33     }
34 
35     public CuratorFramework getClient() {
36         if (client == null) {
37             client = initClient(zkUrl);
38         }else if (!client.getState().equals(CuratorFrameworkState.STARTED)) {
39             client.start();
40         }
41         return client;
42     }
43 
44     /**
45      * 初始化客户端
46      *
47      * @param zkUrl
48      * @return
49      */
50     private CuratorFramework initClient(String zkUrl) {
51         LOG.info("初始化Zookeeper连接...");
52         try {
53             RetryPolicy retryPolicy = new ExponentialBackoffRetry(SESSION_TIME, RETRY_TIMES);
54             CuratorFramework client = CuratorFrameworkFactory.newClient(zkUrl, retryPolicy);
55             client.start();
56             return client;
57         } catch (Throwable e) {
58             LOG.error("Init zk client error with url [{}]", zkUrl, e);
59             throw e;
60         }
61     }
62 
63     @Override
64     protected void finalize() throws Throwable {
65         if (client != null) {
66             client.close();
67         }
68         super.finalize();
69     }
70 
71     @Override
72     public void close() throws IOException {
73         if (client != null) {
74             client.close();
75         }
76     }
77 }

 

zookeeper持有者类

标签:oid   java   except   getc   private   final   super   rri   超时   

原文地址:http://www.cnblogs.com/jinniezheng/p/6384026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!