方式1:
向eurekaServer上注册了两个服务
client1: 9611
client2: 9612
image.png
client1代码:
package com.wuhongyu.eurekaclient.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class TestController {
@GetMapping("/test1")
public String test1(){
return "success";
}
}
client2代码:
package com.wuhongyu.eurekaclient2.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@Slf4j
public class TestController {
@GetMapping("/getClient1Test1")
public String getClient1Test1(){
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:9611/test1";
String response = restTemplate.getForObject(url, String.class);
log.info("response={}",response);
return response;
}
}
请求结果:
image.png
方式2:
client2代码:
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/getClient1Test2")
public String getClient1Test2(){
RestTemplate restTemplate = new RestTemplate();
ServiceInstance client1 = loadBalancerClient.choose("CLIENT1");
String url = String.format("http://%s:%s/test1", client1.getHost(), client1.getPort());
String response = restTemplate.getForObject(url, String.class);
log.info("response={}",response);
return response;
}
方式3:
client2中增一个类: BeanConfig
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class BeanConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
代码:
@Autowired
private RestTemplate restTemplate;
@GetMapping("/getClient1Test3")
public String getClient1Test3(){
String url = "http://CLIENT1/test1";
String response = restTemplate.getForObject(url, String.class);
log.info("response={}",response);
return response;
}
网友评论