Skip to content

Instantly share code, notes, and snippets.

@jkuipers
Created May 31, 2018 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkuipers/cf804bad2e0a19749d26aa200105707e to your computer and use it in GitHub Desktop.
Save jkuipers/cf804bad2e0a19749d26aa200105707e to your computer and use it in GitHub Desktop.
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a list of servers based on resolving the IP addresses of a hostname through DNS.
* Useful when the DNS A-record holds multiple IP addresses that you want to load-balance over.
*/
public class DnsServerList implements ServerList<Server> {
private Logger logger = LoggerFactory.getLogger(getClass());
private String hostname;
public DnsServerList(String hostname) {
this.hostname = hostname;
try {
Security.setProperty("networkaddress.cache.ttl", "0");
} catch (SecurityException e) {
logger.warn("Can't disable DNS cache", e);
}
}
@Override
public List<Server> getInitialListOfServers() {
return getUpdatedListOfServers();
}
@Override
public List<Server> getUpdatedListOfServers() {
List<Server> servers = new ArrayList<>();
try {
for (InetAddress address : InetAddress.getAllByName(hostname)) {
servers.add(new Server(address.getHostAddress()));
}
} catch (UnknownHostException e) {
logger.error("Can't resolve {}: {}", hostname, e.getMessage());
}
logger.debug("Resolved {} to {} Servers", hostname, servers.size());
return servers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment