-
Notifications
You must be signed in to change notification settings - Fork 720
Description
Describe the bug/feture
When using RestTemplate with @LoadBalanced annotation, it cannot make requests to direct addresses like IP addresses (http://192.168.1.110:8080) or localhost (http://localhost:8080). The load balancer interceptor attempts to resolve these through service discovery, causing request failures.
Expected Behavior
@LoadBalanced RestTemplate should intelligently distinguish between:
- Direct requests - IP addresses and localhost calls that should bypass service discovery
- Service discovery requests - Service names that should go through load balancing
Proposed Solution
Modify the load balancer detection logic to identify direct requests by these patterns:
- localhost calls with explicit ports: http://localhost:8080
- IP address calls with explicit ports: http://192.168.1.110:8080
- IPv6 addresses with ports: http://[::1]:8080
Enhancement to Service ID Resolution
For service discovery compatibility:
Change service ID extraction from just host to host:port format
Schema (http/https) can be ignored in service ID resolution as it's not typically relevant for service discovery
This maintains backward compatibility while providing more precise service identification
Sample Code
@Autowired
private RestTemplate loadBalancedRestTemplate;
// Direct requests - should bypass service discovery
loadBalancedRestTemplate.getForObject("http://192.168.1.110:8080/api/test", String.class);
loadBalancedRestTemplate.getForObject("http://localhost:8080/api/test", String.class);
loadBalancedRestTemplate.getForObject("http://10.0.0.1:9000/service", String.class);
loadBalancedRestTemplate.getForObject("http://[::1]:8080/ipv6", String.class);
// Service discovery requests - should use load balancing
loadBalancedRestTemplate.getForObject("http://user-service/api/users", String.class);Benefits
Single RestTemplate instance can handle both direct and service calls
Enhanced service ID resolution using host:port improves service discovery precision
Maintains full backward compatibility
Better developer experience without requiring multiple RestTemplate instances
Environment
Spring Cloud Commons version: [4.3.0]