Debian Codegraph @

curator-examples/src/main/java/leader/LeaderSelectorExample.java

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package leader;
21
22 import com.google.common.collect.Lists;
23 import java.io.BufferedReader;
24 import java.io.InputStreamReader;
25 import java.util.List;
26 import org.apache.curator.framework.CuratorFramework;
27 import org.apache.curator.framework.CuratorFrameworkFactory;
28 import org.apache.curator.retry.ExponentialBackoffRetry;
29 import org.apache.curator.test.TestingServer;
30 import org.apache.curator.utils.CloseableUtils;
31
32 public class LeaderSelectorExample {
33 private static final int CLIENT_QTY = 10;
34
35 private static final String PATH = "/examples/leader";
36
37 public static void main(String[] args) throws Exception {
38 // all of the useful sample code is in ExampleClient.java
39
40 System.out.println(
41 "Create " + CLIENT_QTY
42 + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur.");
43 System.out.println(
44 "Notice that leader election is fair: all clients will become leader and will do so the same number of times.");
45
46 List<CuratorFramework> clients = Lists.newArrayList();
47 List<ExampleClient> examples = Lists.newArrayList();
48 TestingServer server = new TestingServer();
49 try {
50 for (int i = 0; i < CLIENT_QTY; ++i) {
51 CuratorFramework client = CuratorFrameworkFactory.newClient(
52 server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
53 clients.add(client);
54
55 ExampleClient example = new ExampleClient(client, PATH, "Client #" + i);
56 examples.add(example);
57
58 client.start();
59 example.start();
60 }
61
62 System.out.println("Press enter/return to quit\n");
63 new BufferedReader(new InputStreamReader(System.in)).readLine();
64 } finally {
65 System.out.println("Shutting down...");
66
67 for (ExampleClient exampleClient : examples) {
68 CloseableUtils.closeQuietly(exampleClient);
69 }
70 for (CuratorFramework client : clients) {
71 CloseableUtils.closeQuietly(client);
72 }
73
74 CloseableUtils.closeQuietly(server);
75 }
76 }
77 }