zookeeper持有者类
Posted 金聂政
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zookeeper持有者类相关的知识,希望对你有一定的参考价值。
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持有者类的主要内容,如果未能解决你的问题,请参考以下文章
Android TabLayout ViewPager 不会在 backstack 上膨胀标签片段