package com.mobanker.config.bsw.zookeeperScheme.factory; import java.util.HashMap; import java.util.Map; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryUntilElapsed; /** * Copyright @ 2013QIANLONG. All right reserved. Class Name : * com.mobanker.config.core.factory Description : Author : gaohailiang Date : * 2016/1/15 */ public class ZookeeperFactory { public static final int MAX_RETRIES = 3; public static final int BASE_SLEEP_TIMEMS = 1000; public static final int MAX_ELAPSED_TIMEMS = 1000; public static final int SLEEP_MS_BETWEEN_RETRIES = 50; public static Map<String, CuratorFramework> clientPool = new HashMap<>(); public synchronized static CuratorFramework getByZookeeperConfig(ZookeeperConfig zookeeperConfig) { if (clientPool.get(zookeeperConfig.getNameSpace()) == null) { RetryPolicy retryUntilElapsedPolicy = new RetryUntilElapsed(MAX_ELAPSED_TIMEMS, SLEEP_MS_BETWEEN_RETRIES); CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zookeeperConfig.getConnection()) .retryPolicy(retryUntilElapsedPolicy).namespace(zookeeperConfig.getNameSpace()).connectionTimeoutMs(5000).build(); client.start(); clientPool.put(zookeeperConfig.getNameSpace(), client); } return clientPool.get(zookeeperConfig.getNameSpace()); } public static void closeByZkConfig(ZookeeperConfig zookeeperConfig) { CuratorFramework client = clientPool.get(zookeeperConfig.getNameSpace()); if (client != null) { client.close(); clientPool.remove(zookeeperConfig.getNameSpace()); } } public static void close() { CuratorFramework client = clientPool.get(""); if (client != null) { client.close(); clientPool.remove(""); } } public synchronized static CuratorFramework get(Map<String, String> zookeeperConfigMap) { if (clientPool.get("") == null) { RetryPolicy retryUntilElapsedPolicy = new RetryUntilElapsed(MAX_ELAPSED_TIMEMS, SLEEP_MS_BETWEEN_RETRIES); String connection = zookeeperConfigMap.get(ZkConstants.KEY_ZK_CONNECTSTRING); if (ValidateUtil.isNullOrEmpty(connection)) { return null; } Integer timeOutMs = 30000; if (!ValidateUtil.isNullOrEmpty(zookeeperConfigMap.get(ZkConstants.KEY_ZK_CONNECTIONTIMEOUT))) { timeOutMs = Integer.valueOf(zookeeperConfigMap.get(ZkConstants.KEY_ZK_CONNECTIONTIMEOUT)); } CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connection).retryPolicy(retryUntilElapsedPolicy) .connectionTimeoutMs(timeOutMs).build(); client.start(); clientPool.put("", client); } return clientPool.get(""); } public static CuratorFramework get() { if (clientPool == null) { return null; } return clientPool.get(""); } }
zookeeper
最新推荐文章于 2023-08-03 22:51:05 发布