赞
踩
目录
父项目版本详见:https://blog.csdn.net/bfss_11/article/details/119056522
涉及到的文件
在前一篇搭建eureka服务过程中,实际已经使用到了ribbon。因为在eureka中已经包含了ribbon相关依赖,所以不需要额外引入ribbon依赖。
下面为eureka依赖,已包含ribbon相关
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
- <exclusions>
- <exclusion>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
使用:
在resttemplate上添加@LoadBalanced启动负重均衡,默认采用轮询算法
- @Bean
- @LoadBalanced
- public RestTemplate restTemplate() {
- return new RestTemplate();
- }
spring-cloud-starter-netflix-eureka-client 2.2.9.RELEASE及之前的版本
通过@Bean方式注册随机算法。类名上需要添加@Configuration
- package com.zy.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import com.netflix.loadbalancer.IRule;
- import com.netflix.loadbalancer.RandomRule;
-
- @Configuration
- public class MyRule {
-
- @Bean
- IRule myRandomRule() {
- return new RandomRule();
- }
-
- }
继承AbstractLoadBalancerRule。
该算法思路为:每个服务调用3次,示例如下。
-
- package com.zy.config;
-
- import java.util.List;
-
- import org.apache.commons.collections4.CollectionUtils;
- import com.netflix.client.config.IClientConfig;
- import com.netflix.loadbalancer.AbstractLoadBalancerRule;
- import com.netflix.loadbalancer.ILoadBalancer;
- import com.netflix.loadbalancer.Server;
-
- public class MyLoadBalancer extends AbstractLoadBalancerRule {
-
- private int total = 0;// 调用了几次
- private int currentIndex = 0;// 当前调用者
-
- @Override
- public Server choose(Object key) {
- return choose(getLoadBalancer(), key);
- }
-
- private Server choose(ILoadBalancer lb, Object key) {
- if (lb == null) {
- return null;
- }
- List<Server> reachableServers = lb.getReachableServers();
- if (CollectionUtils.isEmpty(reachableServers)) {
- return null;
- }
-
- Server server = null;
- if (total < 3) {
- server = reachableServers.get(currentIndex);
- total++;
- } else {
- total = 1;
- currentIndex++;
- if (currentIndex >= reachableServers.size()) {
- currentIndex = 0;
- }
- server = reachableServers.get(currentIndex);
- }
- return server;
- }
-
- @Override
- public void initWithNiwsConfig(IClientConfig clientConfig) {
- // TODO Auto-generated method stub
-
- }
-
- }
注册该负载均衡算法
3.0.0及之后的版本负载均衡算法继承自ReactorLoadBalancer
- @Bean
- ReactorLoadBalancer<ServiceInstance> myRandomLoadBalancer(Environment environment,
- LoadBalancerClientFactory loadBalancerClientFactory) {
- String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
- return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),
- name);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。