SpringCloud-LoadBalancerClient

源码地址

创建一个SpringBoot项目

SpringCloud-LoadBalancerClient_第1张图片
取名为:eureka-consumerSpringCloud-LoadBalancerClient_第2张图片

添加相关依赖:


    
        org.springframework.cloud
        spring-cloud-starter-eureka
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-actuator
    

配置application.properties
spring.application.name=eureka-consumer
server.port=2101
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
在启动类初始化RestTemplate并添加@EnableDiscoveryClient

SpringCloud-LoadBalancerClient_第3张图片

创建一个controller用来消费eureka-client
@RestController
public class ZxController {
    @Resource
    LoadBalancerClient loadBalancerClient;
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String zx() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }
}

然后依次启动SpringCloud-LoadBalancerClient_第4张图片

访问http://localhost:2101/consumer

你可能感兴趣的:(SpringCloud)