@RestController public class ClientController { @Autowired private LoadBalancerClient loadBalancerClient; // @Autowired // private RestTemplate template; @GetMapping("/msg") public String msg() { // 方式一(写死url,部署的ip未知,负载均衡时,访问服务器未知) // RestTemplate restTemplate = new RestTemplate(); // String response = restTemplate.getForObject("http://localhost:8080/product/getMsg", String.class); // 方式二:使用loadBalancerClient动态拼接url ServiceInstance serviceInstance = loadBalancerClient.choose("product"); String host = serviceInstance.getHost(); int port = serviceInstance.getPort(); String url = String.format("http://%s:%s", host,port) + "/product/getMsg"; RestTemplate template = new RestTemplate(); String response = template.getForObject(url, String.class); //方式三:采用配置类方式(使用@LoadBalanced)http://product=》http://serviceId // String response = template.getForObject("http://product/product/getMsg", String.class); System.out.println(response); return response; } } -------------------------------------------------- @Configuration public class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }