查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * A {@link NameResolver} that resolves {@link InetAddress} and force Round Robin by choosing a single address
33   * randomly in {@link #resolve(String)} and {@link #resolve(String, Promise)}
34   * if multiple are returned by the {@link NameResolver}.
35   * Use {@link #asAddressResolver()} to create a {@link InetSocketAddress} resolver
36   */
37  public class RoundRobinInetAddressResolver extends InetNameResolver {
38      private final NameResolver<InetAddress> nameResolver;
39  
40      /**
41       * @param executor the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned by
42       * {@link #resolve(String)}
43       * @param nameResolver the {@link NameResolver} used for name resolution
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          // hijack the doResolve request, but do a doResolveAll request under the hood.
53          // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
54          // because an unresolved address always has a host name.
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                          // if there are multiple addresses: we shall pick one by one
63                          // to support the round robin distribution
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                          // create a copy to make sure that it's modifiable random access collection
84                          List<InetAddress> result = new ArrayList<InetAddress>(inetAddresses);
85                          // rotate by different distance each time to force round robin distribution
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 }