From e849afbb23ada657b8bee3fd368ae844af418507 Mon Sep 17 00:00:00 2001 From: md_5 Date: Fri, 20 Jun 2014 20:04:22 +1000 Subject: [PATCH] Add simple address cache for those with slow or otherwise unresponsive DNS servers. I wonder when @netty was supposed to add async dns lookups. --- .../java/net/md_5/bungee/http/HttpClient.java | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/proxy/src/main/java/net/md_5/bungee/http/HttpClient.java b/proxy/src/main/java/net/md_5/bungee/http/HttpClient.java index 740e6716..e1f2c1b6 100644 --- a/proxy/src/main/java/net/md_5/bungee/http/HttpClient.java +++ b/proxy/src/main/java/net/md_5/bungee/http/HttpClient.java @@ -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 addressCache = CacheBuilder.newBuilder().expireAfterWrite( 5, TimeUnit.MINUTES ).build(); public static void get(String url, EventLoop eventLoop, final Callback 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 ); } }