首页 > 代码库 > zookeeper持有者类
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持有者类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。