org.apache.curator.retry.ExponentialBackoffRetry Java Examples
The following examples show how to use
org.apache.curator.retry.ExponentialBackoffRetry.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZkReentrantLockTemplateTest.java From Mykit with Apache License 2.0 | 6 votes |
public static void main(String[] args) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); client.start(); final ZkDistributedLockTemplate template = new ZkDistributedLockTemplate(client);// 本类多线程安全,可通过spring注入 template.execute("订单流水号", 5000, new Callback() { @Override public Object onGetLock() throws InterruptedException { // TODO 获得锁后要做的事 return null; } @Override public Object onTimeout() throws InterruptedException { // TODO 获得锁超时后要做的事 return null; } }); }
Example #2
Source File: ZkMutexDistributedLockFactory.java From gpmall with Apache License 2.0 | 6 votes |
/** * 初始化 */ private static synchronized void init() { if(client==null){ //TODO zk地址 String IPAndPort = ""; //TODO 项目名 String projectName = ""; if(StringUtils.isEmpty(IPAndPort) || StringUtils.isEmpty(projectName)){ logger.error("zk锁启动失败缺少配置--IP和端口号/项目名"); throw new RuntimeException("zk锁启动异常--缺少配置--IP和端口号/项目名"); } ZkMutexDistributedLockFactory.projectName = projectName+"/"; client = CuratorFrameworkFactory.builder() .connectString(IPAndPort) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); client.start(); // 启动后台线程 LockBackGroundThread backGroundThread = new LockBackGroundThread(client); backGroundThread.start(); } }
Example #3
Source File: TestRetryLoop.java From xian with Apache License 2.0 | 6 votes |
@Test public void testExponentialBackoffRetryLimit() { RetrySleeper sleeper = new RetrySleeper() { @Override public void sleepFor(long time, TimeUnit unit) throws InterruptedException { Assert.assertTrue(unit.toMillis(time) <= 100); } }; ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1, Integer.MAX_VALUE, 100); for ( int i = 0; i >= 0; ++i ) { retry.allowRetry(i, 0, sleeper); } }
Example #4
Source File: ZookeeperOffsetHandler.java From flink with Apache License 2.0 | 6 votes |
public ZookeeperOffsetHandler(Properties props) { this.groupId = props.getProperty(ConsumerConfig.GROUP_ID_CONFIG); if (this.groupId == null) { throw new IllegalArgumentException("Required property '" + ConsumerConfig.GROUP_ID_CONFIG + "' has not been set"); } String zkConnect = props.getProperty("zookeeper.connect"); if (zkConnect == null) { throw new IllegalArgumentException("Required property 'zookeeper.connect' has not been set"); } // we use Curator's default timeouts int sessionTimeoutMs = Integer.valueOf(props.getProperty("zookeeper.session.timeout.ms", "60000")); int connectionTimeoutMs = Integer.valueOf(props.getProperty("zookeeper.connection.timeout.ms", "15000")); // undocumented config options allowing users to configure the retry policy. (they are "flink." prefixed as they are no official kafka configs) int backoffBaseSleepTime = Integer.valueOf(props.getProperty("flink.zookeeper.base-sleep-time.ms", "100")); int backoffMaxRetries = Integer.valueOf(props.getProperty("flink.zookeeper.max-retries", "10")); RetryPolicy retryPolicy = new ExponentialBackoffRetry(backoffBaseSleepTime, backoffMaxRetries); curatorClient = CuratorFrameworkFactory.newClient(zkConnect, sessionTimeoutMs, connectionTimeoutMs, retryPolicy); curatorClient.start(); }
Example #5
Source File: TestInterProcessMutexBase.java From xian with Apache License 2.0 | 6 votes |
@Test public void testWithNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new ExponentialBackoffRetry(100, 3)). namespace("test"). build(); client.start(); try { InterProcessLock mutex = makeLock(client); mutex.acquire(10, TimeUnit.SECONDS); Thread.sleep(100); mutex.release(); } finally { client.close(); } }
Example #6
Source File: ServiceManageControllerTest.java From sofa-dashboard with Apache License 2.0 | 6 votes |
@Before public void before() throws Exception { restTemplate = new RestTemplate(); // 初始化 zk 节点 client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry( 1000, 3)); client.start(); int index = 0; while (registryDataCache.fetchService().size() == 0 && index++ < tryTimes) { initZookeeperRpcData(); } if (registryDataCache.fetchService().size() == 0) { List<RpcService> providerList = new ArrayList<>(); RpcService rpcService = new RpcService(); rpcService.setServiceName("serviceId1"); providerList.add(rpcService); registryDataCache.addService(providerList); } }
Example #7
Source File: StateKeeper.java From DDMQ with Apache License 2.0 | 6 votes |
public void start() throws Exception { if (StringUtils.isEmpty(namesrvController.getNamesrvConfig().getClusterName()) || StringUtils.isEmpty(namesrvController.getNamesrvConfig().getZkPath())) { log.error("clusterName:{} or zk path:{} is empty", namesrvController.getNamesrvConfig().getClusterName(), namesrvController.getNamesrvConfig().getZkPath()); throw new Exception("cluster name or zk path is null"); } hostName = getHostName(); zkClient = CuratorFrameworkFactory.newClient(namesrvController.getNamesrvConfig().getZkPath(), SESSION_TIMEOUT_MS, CONNECTION_TIMEOUT_MS, new ExponentialBackoffRetry(RETRY_INTERVAL_MS, RETRY_COUNT)); zkClient.getConnectionStateListenable().addListener(new StateListener()); zkClient.start(); createRootPath(); registerLeaderLatch(); }
Example #8
Source File: SimpleLeaderManager.java From mykit-delay with Apache License 2.0 | 6 votes |
public void init() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(properties.getServerList()) .retryPolicy(new ExponentialBackoffRetry(properties.getBaseSleepTimeMilliseconds(), properties.getMaxRetries(), properties.getMaxSleepTimeMilliseconds())) .namespace(ServerNode.NAMESPACE); framework = builder.build(); framework.start(); leaderLatch = new LeaderLatch(framework, ServerNode.LEADERLATCH, serverName, LeaderLatch.CloseMode.NOTIFY_LEADER); for (LeaderLatchListener listener : listeners) { leaderLatch.addListener(listener); } LOGGER.info("starting Queue Master Slave Model ..."); start(); }
Example #9
Source File: ZookeeperOffsetHandler.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
public ZookeeperOffsetHandler(Properties props) { this.groupId = props.getProperty(ConsumerConfig.GROUP_ID_CONFIG); if (this.groupId == null) { throw new IllegalArgumentException("Required property '" + ConsumerConfig.GROUP_ID_CONFIG + "' has not been set"); } String zkConnect = props.getProperty("zookeeper.connect"); if (zkConnect == null) { throw new IllegalArgumentException("Required property 'zookeeper.connect' has not been set"); } // we use Curator's default timeouts int sessionTimeoutMs = Integer.valueOf(props.getProperty("zookeeper.session.timeout.ms", "60000")); int connectionTimeoutMs = Integer.valueOf(props.getProperty("zookeeper.connection.timeout.ms", "15000")); // undocumented config options allowing users to configure the retry policy. (they are "flink." prefixed as they are no official kafka configs) int backoffBaseSleepTime = Integer.valueOf(props.getProperty("flink.zookeeper.base-sleep-time.ms", "100")); int backoffMaxRetries = Integer.valueOf(props.getProperty("flink.zookeeper.max-retries", "10")); RetryPolicy retryPolicy = new ExponentialBackoffRetry(backoffBaseSleepTime, backoffMaxRetries); curatorClient = CuratorFrameworkFactory.newClient(zkConnect, sessionTimeoutMs, connectionTimeoutMs, retryPolicy); curatorClient.start(); }
Example #10
Source File: StateKeeper.java From DDMQ with Apache License 2.0 | 6 votes |
public void start() throws Exception { if (StringUtils.isEmpty(namesrvController.getNamesrvConfig().getClusterName()) || StringUtils.isEmpty(namesrvController.getNamesrvConfig().getZkPath())) { log.error("clusterName:{} or zk path:{} is empty", namesrvController.getNamesrvConfig().getClusterName(), namesrvController.getNamesrvConfig().getZkPath()); throw new Exception("cluster name or zk path is null"); } hostName = getHostName(); zkClient = CuratorFrameworkFactory.newClient(namesrvController.getNamesrvConfig().getZkPath(), SESSION_TIMEOUT_MS, CONNECTION_TIMEOUT_MS, new ExponentialBackoffRetry(RETRY_INTERVAL_MS, RETRY_COUNT)); zkClient.getConnectionStateListenable().addListener(new StateListener()); zkClient.start(); createRootPath(); registerLeaderLatch(); }
Example #11
Source File: BeihuZookeeperAutoConfiguration.java From beihu-boot with Apache License 2.0 | 6 votes |
@Bean(name = "curatorFramework") @ConditionalOnMissingBean(name = "curatorFramework") protected CuratorFramework curatorFramework() throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(beihuZookeeperProperties.getRetryPolicy().getBaseSleepTime(), beihuZookeeperProperties.getRetryPolicy().getRetryNum(), beihuZookeeperProperties.getRetryPolicy().getMaxSleepTime()); return CuratorFrameworkFactory.builder() .connectString(beihuZookeeperProperties.getZhosts()) .sessionTimeoutMs(beihuZookeeperProperties.getSessionTimeout()) // .connectionTimeoutMs(beihuZookeeperProperties.getConnectionTimeout()) .namespace(beihuZookeeperProperties.getNamespace()) .retryPolicy(retryPolicy) .build(); }
Example #12
Source File: ZKDiscoveryServiceImpl.java From YuRPC with Apache License 2.0 | 6 votes |
/** * 初始化方法,(仅在使用无参构造器时使用) * * @param zookeeper * @throws java.lang.Throwable 异常 */ public void init(String zookeeper) throws Throwable { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); this.client = CuratorFrameworkFactory.newClient(zookeeper, retryPolicy); this.client.start(); this.client.getConnectionStateListenable().addListener((ConnectionStateListener) (CuratorFramework cf, ConnectionState cs) -> { if (cs == ConnectionState.RECONNECTED) { if (pathValue != null && !pathValue.isEmpty()) { pathValue.entrySet().forEach((entry) -> { String path = entry.getKey(); byte[] value = entry.getValue(); try { cf.create().withMode(CreateMode.EPHEMERAL).forPath(path, value); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } }); } } }, watcherExecutorService); }
Example #13
Source File: ZkConfig.java From spring-boot-demo with MIT License | 5 votes |
@Bean public CuratorFramework curatorFramework() { RetryPolicy retryPolicy = new ExponentialBackoffRetry(zkProps.getTimeout(), zkProps.getRetry()); CuratorFramework client = CuratorFrameworkFactory.newClient(zkProps.getUrl(), retryPolicy); client.start(); return client; }
Example #14
Source File: ZkClient.java From rpcx-java with Apache License 2.0 | 5 votes |
private ZkClient() { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); String cs = Config.ins().get("rpcx.zk.connect.string"); client = CuratorFrameworkFactory.builder() .connectString(cs) .sessionTimeoutMs(5000) .connectionTimeoutMs(5000) .retryPolicy(retryPolicy) .build(); client.start(); }
Example #15
Source File: ZookeeperRuleConfigSource.java From ratelimiter4j with Apache License 2.0 | 5 votes |
private void initialClient() { if (!isInitialized.compareAndSet(false, true)) { return; } if (client == null && StringUtils.isEmpty(address)) { throw new RuntimeException("zookeeper server address is not set."); } boolean connected = false; try { if (client == null) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries); client = CuratorFrameworkFactory.builder().connectString(address).retryPolicy(retryPolicy) .connectionTimeoutMs(connectionTimeout).sessionTimeoutMs(sessionTimeout).build(); } client.start(); connected = client.blockUntilConnected(connectionTimeout, TimeUnit.MILLISECONDS); if (!connected) { throw new RuntimeException("connect zookeeper failed."); } } catch (Exception e) { CloseableUtils.closeQuietly(client); isInitialized.compareAndSet(true, false); throw new RuntimeException("init zookeeper client error.", e); } }
Example #16
Source File: ZKTools.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void generateDubboProperties() { client = CuratorFrameworkFactory.newClient(zookeeperHost + ":2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); generateDubboPropertiesForGlobal(); generateDubboPropertiesForConsumer(); }
Example #17
Source File: ZookeeperConfigSender.java From Sentinel with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { final String remoteAddress = "localhost:2181"; final String groupId = "Sentinel-Demo"; final String dataId = "SYSTEM-CODE-DEMO-FLOW"; final String rule = "[\n" + " {\n" + " \"resource\": \"TestResource\",\n" + " \"controlBehavior\": 0,\n" + " \"count\": 10.0,\n" + " \"grade\": 1,\n" + " \"limitApp\": \"default\",\n" + " \"strategy\": 0\n" + " }\n" + "]"; CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES)); zkClient.start(); String path = getPath(groupId, dataId); Stat stat = zkClient.checkExists().forPath(path); if (stat == null) { zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null); } zkClient.setData().forPath(path, rule.getBytes()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } zkClient.close(); }
Example #18
Source File: ZkReentrantLockCleanerTask.java From Mykit with Apache License 2.0 | 5 votes |
public ZkReentrantLockCleanerTask(String zookeeperAddress) { try { RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries); client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy); client.start(); } catch (Exception e) { log.error(e.getMessage(), e); } catch (Throwable ex) { ex.printStackTrace(); log.error(ex.getMessage(), ex); } }
Example #19
Source File: ZKTools.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void generateDubboProperties() { client = CuratorFrameworkFactory.newClient(zookeeperHost + ":2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); generateDubboPropertiesForGlobal(); generateDubboPropertiesForConsumer(); }
Example #20
Source File: ZkReentrantLockTemplateTest.java From Mykit with Apache License 2.0 | 5 votes |
@Test public void testTry() throws InterruptedException { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); client.start(); final ZkDistributedLockTemplate template = new ZkDistributedLockTemplate(client); int size = 100; final CountDownLatch startCountDownLatch = new CountDownLatch(1); final CountDownLatch endDownLatch = new CountDownLatch(size); for (int i = 0; i < size; i++) { new Thread() { public void run() { try { startCountDownLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } final int sleepTime = ThreadLocalRandom.current().nextInt(5) * 1000; template.execute("test", 5000, new Callback() { public Object onGetLock() throws InterruptedException { System.out.println(Thread.currentThread().getName() + ":getLock"); Thread.sleep(sleepTime); System.out.println(Thread.currentThread().getName() + ":sleeped:" + sleepTime); endDownLatch.countDown(); return null; } public Object onTimeout() throws InterruptedException { System.out.println(Thread.currentThread().getName() + ":timeout"); endDownLatch.countDown(); return null; } }); } }.start(); } startCountDownLatch.countDown(); endDownLatch.await(); }
Example #21
Source File: DiscoveryExample.java From xian with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // This method is scaffolding to get the example up and running TestingServer server = new TestingServer(); CuratorFramework client = null; ServiceDiscovery<InstanceDetails> serviceDiscovery = null; Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap(); try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class); serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build(); serviceDiscovery.start(); processCommands(serviceDiscovery, providers, client); } finally { for ( ServiceProvider<InstanceDetails> cache : providers.values() ) { CloseableUtils.closeQuietly(cache); } CloseableUtils.closeQuietly(serviceDiscovery); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server); } }
Example #22
Source File: ZKTools.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void generateDubboProperties() { client = CuratorFrameworkFactory.newClient(zookeeperHost + ":2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); generateDubboPropertiesForGlobal(); generateDubboPropertiesForProvider(); generateDubboPropertiesForConsumer(); }
Example #23
Source File: TestLockACLs.java From xian with Apache License 2.0 | 5 votes |
private CuratorFramework createClient(ACLProvider provider) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() .namespace("ns") .connectString(server.getConnectString()) .retryPolicy(retryPolicy) .aclProvider(provider) .build(); client.start(); return client; }
Example #24
Source File: TestLeaderSelectorWithExecutor.java From xian with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { Timing timing = new Timing(); LeaderSelector leaderSelector = null; CuratorFramework client = CuratorFrameworkFactory.builder() .retryPolicy(new ExponentialBackoffRetry(100, 3)) .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .build(); try { client.start(); MyLeaderSelectorListener listener = new MyLeaderSelectorListener(); ExecutorService executorPool = Executors.newFixedThreadPool(20); leaderSelector = new LeaderSelector(client, "/test", threadFactory, executorPool, listener); leaderSelector.autoRequeue(); leaderSelector.start(); timing.sleepABit(); Assert.assertEquals(listener.getLeaderCount(), 1); } finally { CloseableUtils.closeQuietly(leaderSelector); CloseableUtils.closeQuietly(client); } }
Example #25
Source File: ZKTools.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void generateDubboProperties() { client = CuratorFrameworkFactory.newClient(zookeeperHost + ":2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); generateDubboPropertiesForGlobal(); }
Example #26
Source File: ZKTools.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); configuratorsApp(); System.in.read(); }
Example #27
Source File: ZooKeeperConfigSourceTest.java From smallrye-config with Apache License 2.0 | 5 votes |
@BeforeAll static void setUpClass() throws Exception { testServer = new TestingServer(2181, true); //Add a property that's going to be injected curatorClient = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(1000, 3)); curatorClient.start(); curatorClient.createContainers("/test1/injected.property"); curatorClient.setData().forPath("/test1/injected.property", "injected.property.value".getBytes()); curatorClient.createContainers("/test1/injected.int.property"); curatorClient.setData().forPath("/test1/injected.int.property", "17".getBytes()); }
Example #28
Source File: ZooKeeperConfigSource.java From smallrye-config with Apache License 2.0 | 5 votes |
public ZooKeeperConfigSource(final String zookeeperUrl, final String applicationId) { super(ZOOKEEPER_CONFIG_SOURCE_NAME, 150); //Only create the ZK Client if the properties exist. if (zookeeperUrl != null && applicationId != null) { ZooKeepperLogging.log.configuringZookeeper(zookeeperUrl, applicationId); this.applicationId = applicationId.startsWith("/") ? applicationId : "/" + applicationId; this.curator = CuratorFrameworkFactory.newClient(zookeeperUrl, new ExponentialBackoffRetry(1000, 3)); this.curator.start(); } else { throw ZooKeeperMessages.msg.propertiesNotSet(); } }
Example #29
Source File: ZookeeperConfig.java From springboot-plus with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Bean public CuratorFramework getCuratorFramework() throws Exception { String zkUrl = env.getProperty("zookeeper.url"); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient(zkUrl, retryPolicy); client.start(); return client; }
Example #30
Source File: ZKRegistry.java From joyrpc with Apache License 2.0 | 5 votes |
@Override protected CompletableFuture<Void> doConnect() { return Futures.call(future -> { CuratorFramework client = CuratorFrameworkFactory.builder().connectString(registry.address) .sessionTimeoutMs(registry.sessionTimeout) .connectionTimeoutMs(registry.connectionTimeout) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); client.start(); client.getConnectionStateListenable().addListener((curator, state) -> { if (!isOpen()) { doDisconnect().whenComplete((v, t) -> future.completeExceptionally(new IllegalStateException("controller is closed."))); } else if (state.isConnected()) { logger.warn("zk connection state is changed to " + state + "."); if (future.isDone()) { //重新注册 registers.forEach((k, r) -> addBookingTask(registers, r, this::doRegister)); } else { future.complete(null); } } else { //会自动重连 logger.warn("zk connection state is changed to " + state + "."); } }); curator = AsyncCuratorFramework.wrap(client); }); }