Add simple address cache for those with slow or otherwise unresponsive DNS servers.

I wonder when @netty was supposed to add async dns lookups.
This commit is contained in:
md_5 2014-06-20 20:04:22 +10:00
parent 1a7efeabc4
commit e849afbb23

View File

@ -1,19 +1,23 @@
package net.md_5.bungee.http;
import com.google.common.base.Preconditions;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.md_5.bungee.api.Callback;
@ -22,7 +26,8 @@ import net.md_5.bungee.api.Callback;
public class HttpClient
{
public static int TIMEOUT = 5000;
public static final int TIMEOUT = 5000;
private static final Cache<String, InetAddress> addressCache = CacheBuilder.newBuilder().expireAfterWrite( 5, TimeUnit.MINUTES ).build();
public static void get(String url, EventLoop eventLoop, final Callback<String> callback)
{
@ -51,6 +56,20 @@ public class HttpClient
}
}
InetAddress inetHost = addressCache.getIfPresent( uri.getHost() );
if ( inetHost == null )
{
try
{
inetHost = InetAddress.getByName( uri.getHost() );
} catch ( UnknownHostException ex )
{
callback.done( null, ex );
return;
}
}
addressCache.put( uri.getHost(), inetHost );
ChannelFutureListener future = new ChannelFutureListener()
{
@Override
@ -72,6 +91,6 @@ public class HttpClient
};
new Bootstrap().channel( NioSocketChannel.class ).group( eventLoop ).handler( new HttpInitializer( callback, ssl ) ).
option( ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT ).remoteAddress( uri.getHost(), port ).connect().addListener( future );
option( ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT ).remoteAddress( inetHost, port ).connect().addListener( future );
}
}