考虑以下代码:
ResponseEntity<String> response = restTemplate.exchange("http://balanced.domain.com:9000/api/endpoint", HttpMethod.PUT, requestObject, String.class);
balanced.domain.com
指向多个IP均衡DNS,请说1.1.1.1
和2.2.2.2
。
如果我多次(循环)执行交换请求,所有请求都会被发送到同一个IP(让我们说1.1.1.1
),即这两个IP和#39之间没有平衡负载; S
所有这一切都需要在JVM中配置参数,以便使用$JAVA_HOME/jre/lib/security/java.security
(不同于-1)在networkaddress.cache.ttl=0
上刷新DNS信息。
我实施的丑陋解决方案看起来像这样:
InetAddress address = InetAddress.getByName("balanced.domain.com");
//This gives you a different IP on several executions
String ip = address.getHostAddress();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
requestHeaders.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
//Needed header for routing
requestHeaders.set("Host", "balanced.domain.com:9000");
HttpEntity request = new HttpEntity<>(requestObject, requestHeaders);
//Replacing domain by obtained IP
ResponseEntity<String> response = restTemplate.exchange("http://"+ip+":9000/api/endpoint", method, request, String.class);
此外,要设置Host标头,还需要以下配置sun.net.http.allowRestrictedHeaders=true
,例如setenv.sh
中的Tomcat将为export CATALINA_OPTS=“$CATALINA_OPTS -Dsun.net.http.allowRestrictedHeaders=true”
。
我对这段代码并不感到自豪,所以如果您有不同的方法可以解决这个问题,请分享。