| 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 discovery; |
| 21 |
|
| 22 |
import com.google.common.base.Predicate; |
| 23 |
import com.google.common.collect.Iterables; |
| 24 |
import com.google.common.collect.Lists; |
| 25 |
import com.google.common.collect.Maps; |
| 26 |
import java.io.BufferedReader; |
| 27 |
import java.io.InputStreamReader; |
| 28 |
import java.util.Arrays; |
| 29 |
import java.util.Collection; |
| 30 |
import java.util.List; |
| 31 |
import java.util.Map; |
| 32 |
import org.apache.curator.framework.CuratorFramework; |
| 33 |
import org.apache.curator.framework.CuratorFrameworkFactory; |
| 34 |
import org.apache.curator.retry.ExponentialBackoffRetry; |
| 35 |
import org.apache.curator.test.TestingServer; |
| 36 |
import org.apache.curator.utils.CloseableUtils; |
| 37 |
import org.apache.curator.x.discovery.ServiceDiscovery; |
| 38 |
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; |
| 39 |
import org.apache.curator.x.discovery.ServiceInstance; |
| 40 |
import org.apache.curator.x.discovery.ServiceProvider; |
| 41 |
import org.apache.curator.x.discovery.details.JsonInstanceSerializer; |
| 42 |
import org.apache.curator.x.discovery.strategies.RandomStrategy; |
| 43 |
import org.apache.zookeeper.KeeperException; |
| 44 |
|
| 45 |
public class DiscoveryExample { |
| 46 |
private static final String PATH = "/discovery/example"; |
| 47 |
|
| 48 |
public static void main(String[] args) throws Exception { |
| 49 |
// This method is scaffolding to get the example up and running |
| 50 |
|
| 51 |
TestingServer server = new TestingServer(); |
| 52 |
CuratorFramework client = null; |
| 53 |
ServiceDiscovery<InstanceDetails> serviceDiscovery = null; |
| 54 |
Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap(); |
| 55 |
try { |
| 56 |
client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); |
| 57 |
client.start(); |
| 58 |
|
| 59 |
JsonInstanceSerializer<InstanceDetails> serializer = |
| 60 |
new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class); |
| 61 |
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class) |
| 62 |
.client(client) |
| 63 |
.basePath(PATH) |
| 64 |
.serializer(serializer) |
| 65 |
.build(); |
| 66 |
serviceDiscovery.start(); |
| 67 |
|
| 68 |
processCommands(serviceDiscovery, providers, client); |
| 69 |
} finally { |
| 70 |
for (ServiceProvider<InstanceDetails> cache : providers.values()) { |
| 71 |
CloseableUtils.closeQuietly(cache); |
| 72 |
} |
| 73 |
|
| 74 |
CloseableUtils.closeQuietly(serviceDiscovery); |
| 75 |
CloseableUtils.closeQuietly(client); |
| 76 |
CloseableUtils.closeQuietly(server); |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
private static void processCommands( |
| 81 |
ServiceDiscovery<InstanceDetails> serviceDiscovery, |
| 82 |
Map<String, ServiceProvider<InstanceDetails>> providers, |
| 83 |
CuratorFramework client) |
| 84 |
throws Exception { |
| 85 |
// More scaffolding that does a simple command line processor |
| 86 |
|
| 87 |
printHelp(); |
| 88 |
|
| 89 |
List<ExampleServer> servers = Lists.newArrayList(); |
| 90 |
try { |
| 91 |
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); |
| 92 |
boolean done = false; |
| 93 |
while (!done) { |
| 94 |
System.out.print("> "); |
| 95 |
|
| 96 |
String line = in.readLine(); |
| 97 |
if (line == null) { |
| 98 |
break; |
| 99 |
} |
| 100 |
|
| 101 |
String command = line.trim(); |
| 102 |
String[] parts = command.split("\\s"); |
| 103 |
if (parts.length == 0) { |
| 104 |
continue; |
| 105 |
} |
| 106 |
String operation = parts[0]; |
| 107 |
String args[] = Arrays.copyOfRange(parts, 1, parts.length); |
| 108 |
|
| 109 |
if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) { |
| 110 |
printHelp(); |
| 111 |
} else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) { |
| 112 |
done = true; |
| 113 |
} else if (operation.equals("add")) { |
| 114 |
addInstance(args, client, command, servers); |
| 115 |
} else if (operation.equals("delete")) { |
| 116 |
deleteInstance(args, command, servers); |
| 117 |
} else if (operation.equals("random")) { |
| 118 |
listRandomInstance(args, serviceDiscovery, providers, command); |
| 119 |
} else if (operation.equals("list")) { |
| 120 |
listInstances(serviceDiscovery); |
| 121 |
} |
| 122 |
} |
| 123 |
} finally { |
| 124 |
for (ExampleServer server : servers) { |
| 125 |
CloseableUtils.closeQuietly(server); |
| 126 |
} |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
private static void listRandomInstance( |
| 131 |
String[] args, |
| 132 |
ServiceDiscovery<InstanceDetails> serviceDiscovery, |
| 133 |
Map<String, ServiceProvider<InstanceDetails>> providers, |
| 134 |
String command) |
| 135 |
throws Exception { |
| 136 |
// this shows how to use a ServiceProvider |
| 137 |
// in a real application you'd create the ServiceProvider early for the service(s) you're interested in |
| 138 |
|
| 139 |
if (args.length != 1) { |
| 140 |
System.err.println("syntax error (expected random <name>): " + command); |
| 141 |
return; |
| 142 |
} |
| 143 |
|
| 144 |
String serviceName = args[0]; |
| 145 |
ServiceProvider<InstanceDetails> provider = providers.get(serviceName); |
| 146 |
if (provider == null) { |
| 147 |
provider = serviceDiscovery |
| 148 |
.serviceProviderBuilder() |
| 149 |
.serviceName(serviceName) |
| 150 |
.providerStrategy(new RandomStrategy<InstanceDetails>()) |
| 151 |
.build(); |
| 152 |
providers.put(serviceName, provider); |
| 153 |
provider.start(); |
| 154 |
|
| 155 |
Thread.sleep( |
| 156 |
2500); // give the provider time to warm up - in a real application you wouldn't need to do this |
| 157 |
} |
| 158 |
|
| 159 |
ServiceInstance<InstanceDetails> instance = provider.getInstance(); |
| 160 |
if (instance == null) { |
| 161 |
System.err.println("No instances named: " + serviceName); |
| 162 |
} else { |
| 163 |
outputInstance(instance); |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception { |
| 168 |
// This shows how to query all the instances in service discovery |
| 169 |
|
| 170 |
try { |
| 171 |
Collection<String> serviceNames = serviceDiscovery.queryForNames(); |
| 172 |
System.out.println(serviceNames.size() + " type(s)"); |
| 173 |
for (String serviceName : serviceNames) { |
| 174 |
Collection<ServiceInstance<InstanceDetails>> instances = |
| 175 |
serviceDiscovery.queryForInstances(serviceName); |
| 176 |
System.out.println(serviceName); |
| 177 |
for (ServiceInstance<InstanceDetails> instance : instances) { |
| 178 |
outputInstance(instance); |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
} catch (KeeperException.NoNodeException e) { |
| 183 |
System.err.println("There are no registered instances."); |
| 184 |
} finally { |
| 185 |
CloseableUtils.closeQuietly(serviceDiscovery); |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
private static void outputInstance(ServiceInstance<InstanceDetails> instance) { |
| 190 |
System.out.println("\t" + instance.getPayload().getDescription() + ": " + instance.buildUriSpec()); |
| 191 |
} |
| 192 |
|
| 193 |
private static void deleteInstance(String[] args, String command, List<ExampleServer> servers) { |
| 194 |
// simulate a random instance going down |
| 195 |
// in a real application, this would occur due to normal operation, a crash, maintenance, etc. |
| 196 |
|
| 197 |
if (args.length != 1) { |
| 198 |
System.err.println("syntax error (expected delete <name>): " + command); |
| 199 |
return; |
| 200 |
} |
| 201 |
|
| 202 |
final String serviceName = args[0]; |
| 203 |
ExampleServer server = Iterables.find( |
| 204 |
servers, |
| 205 |
new Predicate<ExampleServer>() { |
| 206 |
@Override |
| 207 |
public boolean apply(ExampleServer server) { |
| 208 |
return server.getThisInstance().getName().endsWith(serviceName); |
| 209 |
} |
| 210 |
}, |
| 211 |
null); |
| 212 |
if (server == null) { |
| 213 |
System.err.println("No servers found named: " + serviceName); |
| 214 |
return; |
| 215 |
} |
| 216 |
|
| 217 |
servers.remove(server); |
| 218 |
CloseableUtils.closeQuietly(server); |
| 219 |
System.out.println("Removed a random instance of: " + serviceName); |
| 220 |
} |
| 221 |
|
| 222 |
private static void addInstance(String[] args, CuratorFramework client, String command, List<ExampleServer> servers) |
| 223 |
throws Exception { |
| 224 |
// simulate a new instance coming up |
| 225 |
// in a real application, this would be a separate process |
| 226 |
|
| 227 |
if (args.length < 2) { |
| 228 |
System.err.println("syntax error (expected add <name> <description>): " + command); |
| 229 |
return; |
| 230 |
} |
| 231 |
|
| 232 |
StringBuilder description = new StringBuilder(); |
| 233 |
for (int i = 1; i < args.length; ++i) { |
| 234 |
if (i > 1) { |
| 235 |
description.append(' '); |
| 236 |
} |
| 237 |
description.append(args[i]); |
| 238 |
} |
| 239 |
|
| 240 |
String serviceName = args[0]; |
| 241 |
ExampleServer server = new ExampleServer(client, PATH, serviceName, description.toString()); |
| 242 |
servers.add(server); |
| 243 |
server.start(); |
| 244 |
|
| 245 |
System.out.println(serviceName + " added"); |
| 246 |
} |
| 247 |
|
| 248 |
private static void printHelp() { |
| 249 |
System.out.println( |
| 250 |
"An example of using the ServiceDiscovery APIs. This example is driven by entering commands at the prompt:\n"); |
| 251 |
System.out.println("add <name> <description>: Adds a mock service with the given name and description"); |
| 252 |
System.out.println("delete <name>: Deletes one of the mock services with the given name"); |
| 253 |
System.out.println("list: Lists all the currently registered services"); |
| 254 |
System.out.println("random <name>: Lists a random instance of the service with the given name"); |
| 255 |
System.out.println("quit: Quit the example"); |
| 256 |
System.out.println(); |
| 257 |
} |
| 258 |
} |