Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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