Ribbon 负载均衡
什么是Ribbon?
Ribbon 是Netflix 公司开源的一个负载均衡的组件 将负载均衡逻辑封装在客户端中 并且运行在客户端的进程里
Ribbon 作为服务消费者的负载均衡器有两种使用方式 一种是和RestTemplate 相结合 另一种是和Feign 相结合 Feign 已经默认集成了Ribbon
什么是负载均衡?
负载均衡是指将负载分摊到多个执行单元上
假如有2000个用户访问服务 如果没有负载均衡 可能全部的服务都访问8001 而8002则没事干 负载均衡的作用就是将负载分摊到多个执行单元上
打开工程 如果没有该工程 点击 https://www.cnblogs.com/chenziyue/p/12482345.html
修改配置文件
server: port: ${PORT:8006} eureka: instance: hostname: eureka-client client: serviceUrl: defaultZone: http://eureka01:8001/eureka/ spring: application: name: eureka-client
添加代码
@RestController public class HiController { @Value("${server.port}") private String port; @Autowired DiscoveryClient discoveryClient; @RequestMapping("/hi/{name}") public String home(@PathVariable String name){ return "hi" + name + "i am port:" + port ; } }
创建新工程(继承父工程)
导入依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> </dependencies>
配置文件
server: port: 8004 eureka: instance: hostname: ribbon-client client: service-url: defaultZone: http://eureka01:8001/eureka/ spring: application: name: ribbon-client
启动类
@SpringBootApplication @EnableDiscoveryClient public class RibbonApp { @Bean // 加载负载均衡 @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } public static void main( String[] args ) { SpringApplication.run(RibbonApp.class); } }
点击
选择你的EurekaClient 点击复制
依次启动
eureka_client是2个服务
打开注册中心界面 查看eureka_client 是否有2个
打开浏览器输入 http://localhost:8004/hi/xxxx
如果出现
修改hosts文件 将eureka-client添加进去即可
再次访问
刷新
可以看到每次访问 都负载到不同的服务器