组团学

实现客户端负载均衡

阅读 (3564425)

1、在没有"服务中心"的情况下,实现客户端负载均衡

1.1、创建Spring Cloud应用,添加Ribbon和Web依赖

1588915391469.png

1588915414374.png

1.2、编写配置

spring.application.name=ribbon
server.port=50005
provider.ribbon.listOfServers=localhost:50003,localhost:50004

1.3、开启客户端负载均衡

@SpringBootApplication public class ConuserApplication { public static void main(String[] args) { SpringApplication.run(ConuserApplication.class, args); } //定义远程调用RestTemplate Bean @Bean @LoadBalanced //开启负载均衡 RestTemplate restTemplate(){ return new RestTemplate(); } }

1.4、编写负载均衡控制器

@RestController public class HelloController { @Autowired RestTemplate restTemplate; @GetMapping("/hello") public String hello(){ return restTemplate.getForObject("http://provider/"+"hello",String.class); } }

1.5、修改Provider项目配置文件

spring.application.name=provider
server.port=${PORT:50003}
provider.name=${NAME:provider-1}
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://eureka01:50001/eureka/,http://eureka02:50002//eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.ip-address=127.0.0.1
eureka.instance.instance-id=${spring.application.name}:${server.port}

1.6、编写配置脚本

1588916380019.png

1588916352520.png

1.7、启动服务提供者和Ribbon应用

访问http://localhost:50005/hello

15889165488701866018.png

1588916558414.png

需要 登录 才可以提问哦