Skip to content

@LoadBalanced RestTemplate should support direct IP address and localhost requests #1601

Description

@xzxiaoshan

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:

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]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions