1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.resolver;
17
18 import io.netty.util.concurrent.EventExecutor;
19 import io.netty.util.concurrent.Future;
20 import io.netty.util.concurrent.FutureListener;
21 import io.netty.util.concurrent.Promise;
22 import io.netty.util.internal.PlatformDependent;
23
24 import java.net.InetAddress;
25 import java.net.InetSocketAddress;
26 import java.net.UnknownHostException;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30
31
32
33
34
35
36
37 public class RoundRobinInetAddressResolver extends InetNameResolver {
38 private final NameResolver<InetAddress> nameResolver;
39
40
41
42
43
44
45 public RoundRobinInetAddressResolver(EventExecutor executor, NameResolver<InetAddress> nameResolver) {
46 super(executor);
47 this.nameResolver = nameResolver;
48 }
49
50 @Override
51 protected void doResolve(final String inetHost, final Promise<InetAddress> promise) throws Exception {
52
53
54
55 nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
56 @Override
57 public void operationComplete(Future<List<InetAddress>> future) throws Exception {
58 if (future.isSuccess()) {
59 List<InetAddress> inetAddresses = future.getNow();
60 int numAddresses = inetAddresses.size();
61 if (numAddresses > 0) {
62
63
64 promise.setSuccess(inetAddresses.get(randomIndex(numAddresses)));
65 } else {
66 promise.setFailure(new UnknownHostException(inetHost));
67 }
68 } else {
69 promise.setFailure(future.cause());
70 }
71 }
72 });
73 }
74
75 @Override
76 protected void doResolveAll(String inetHost, final Promise<List<InetAddress>> promise) throws Exception {
77 nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
78 @Override
79 public void operationComplete(Future<List<InetAddress>> future) throws Exception {
80 if (future.isSuccess()) {
81 List<InetAddress> inetAddresses = future.getNow();
82 if (!inetAddresses.isEmpty()) {
83
84 List<InetAddress> result = new ArrayList<InetAddress>(inetAddresses);
85
86 Collections.rotate(result, randomIndex(inetAddresses.size()));
87 promise.setSuccess(result);
88 } else {
89 promise.setSuccess(inetAddresses);
90 }
91 } else {
92 promise.setFailure(future.cause());
93 }
94 }
95 });
96 }
97
98 private static int randomIndex(int numAddresses) {
99 return numAddresses == 1 ? 0 : PlatformDependent.threadLocalRandom().nextInt(numAddresses);
100 }
101
102 @Override
103 public void close() {
104 nameResolver.close();
105 }
106 }