spring cloud -- Ribbon

  1. 自定義負載均衡策略  
  2. springboot-h2.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule // 自定義使用隨機策略,springboot-h2是服務應用名  
修改調用代碼

  1. @RestController  
  2. public class RestTemplateController {  
  3.     @Autowired  
  4.     private RestTemplate restTemplate;  
  5.       
  6.     @Autowired  
  7.     private LoadBalancerClient loadBalancerClient;  
  8.       
  9.     @GetMapping("/template/{id}")  
  10.     public User findById(@PathVariable Long id) {  
  11.         ServiceInstance serviceInstance = this.loadBalancerClient.choose("springboot-h2");  
  12.         System.out.println("===" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":"  
  13.                 + serviceInstance.getPort());// 打印當前調用服務的信息  
  14.         User u = this.restTemplate.getForObject("http://springboot-h2/user/" + id, User.class);  
  15.         System.out.println(u);  
  16.         return u;  
  17.     }  



Ribbon作爲後端負載均衡器,比Nginx更注重的是請求分發而不是承擔併發,可以直接感知後臺動態變化來指定分發策略。它一共提供了7種負載均衡策略:

策略名 策略聲明 策略描述 實現說明
BestAvailableRule public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule 選擇一個最小的併發請求的server 逐個考察Server,如果Server被tripped了,則忽略,在選擇其中ActiveRequestsCount最小的server
AvailabilityFilteringRule public class AvailabilityFilteringRule extends PredicateBasedRule 過濾掉那些因爲一直連接失敗的被標記爲circuit tripped的後端server,並過濾掉那些高併發的的後端server(active connections 超過配置的閾值) 使用一個AvailabilityPredicate來包含過濾server的邏輯,其實就就是檢查status裏記錄的各個server的運行狀態
WeightedResponseTimeRule public class WeightedResponseTimeRule extends RoundRobinRule 根據響應時間分配一個weight,響應時間越長,weight越小,被選中的可能性越低。 一個後臺線程定期的從status裏面讀取評價響應時間,爲每個server計算一個weight。Weight的計算也比較簡單responsetime 減去每個server自己平均的responsetime是server的權重。當剛開始運行,沒有形成status時,使用roubine策略選擇server。
RetryRule public class RetryRule extends AbstractLoadBalancerRule 對選定的負載均衡策略機上重試機制。 在一個配置時間段內當選擇server不成功,則一直嘗試使用subRule的方式選擇一個可用的server
RoundRobinRule public class RoundRobinRule extends AbstractLoadBalancerRule roundRobin方式輪詢選擇server 輪詢index,選擇index對應位置的server
RandomRule public class RandomRule extends AbstractLoadBalancerRule 隨機選擇一個server 在index上隨機,選擇index對應位置的server
ZoneAvoidanceRule public class ZoneAvoidanceRule extends PredicateBasedRule 複合判斷server所在區域的性能和server的可用性選擇server 使用ZoneAvoidancePredicate和AvailabilityPredicate來判斷是否選擇某個server,前一個判斷判定一個zone的運行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用於過濾掉連接數過多的Server。


    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public IRule ribbonRule() {
        return new RandomRule();//這裏配置策略,和配置文件對應
    }

this.loadBalancerClient.choose("service-B");//隨機訪問策略



配置properties file (sample-client.properties)


# Max number of retries    
ribbon.MaxAutoRetries=1     
# Max number of next servers to retry (excluding the first server)  
ribbon.MaxAutoRetriesNextServer=1 
 # Whether all operations can be retried for this client   
ribbon.OkToRetryOnAllOperations=true  
# Interval to refresh the server list from the source   
ribbon.ServerListRefreshInterval=2000   
# Connect timeout used by Apache HttpClient   
ribbon.ConnectTimeout=3000   
# Read timeout used by Apache HttpClient   
ribbon.ReadTimeout=3000   
# Initial list of servers, can be changed via Archaius dynamic property at runtime   
ribbon.listOfServers=testserver1:80,testserver2 :80,testserver3:80    
ribbon.EnablePrimeConnections=true  

Spring Cloud Netflix provides the following beans by default for ribbon (BeanType beanName: ClassName):

1、IClientConfig ribbonClientConfigDefaultClientConfigImpl

2、IRule ribbonRuleZoneAvoidanceRule

3、IPing ribbonPingNoOpPing

4、ServerList<Server> ribbonServerListConfigurationBasedServerList

5、ServerListFilter<Server> ribbonServerListFilterZonePreferenceServerListFilter

6、ILoadBalancer ribbonLoadBalancerZoneAwareLoadBalancer


1. 如果是對某個服務指定特定的負載均衡策略,則需要使用:RibbonClient註解,如下:

@Configuration
public class FooConfiguration {
    @Bean
    public IPing ribbonPing() {
        return new PingUrl(false,"/info.json");
    }
    /**
     * 負載均衡策略
     * @return
     */
    @Bean
    public IRule ribbonRule() {
//        return new BestAvailableRule(); //選擇一個最小的併發請求的server
//        return new WeightedResponseTimeRule(); //根據相應時間分配一個weight,相應時間越長,weight越小,被選中的可能性越低。
//        return new RetryRule(); //對選定的負載均衡策略機上重試機制。
//        return new RoundRobinRule(); //roundRobin方式輪詢選擇server
//        return new RandomRule(); //隨機選擇一個server
//        return new ZoneAvoidanceRule(); //複合判斷server所在區域的性能和server的可用性選擇server
        return new AvailabilityFilteringRule();
    }
}

聲明特定服務(foo)配置

@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}

name:特定服務名稱


2.

對所有服務指定特定負載均衡策略

指定所有服務的負載均衡策略使用註解:RibbonClients
import com.netflix.loadbalancer.AvailabilityFilteringRule;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * Created by meyer on 2017/2/22.
 */
@Configuration
public class RibbonConfiguration {
    /**
     * ping中心
     * @return
     */
    @Bean
    public IPing ribbonPing() {
        return new PingUrl(false, "/info.json");
    }
    /**
     * 負載均衡策略
     * @return
     */
    @Bean
    public IRule ribbonRule() {
//        return new BestAvailableRule(); //選擇一個最小的併發請求的server
//        return new WeightedResponseTimeRule(); //根據相應時間分配一個weight,相應時間越長,weight越小,被選中的可能性越低。
//        return new RetryRule(); //對選定的負載均衡策略機上重試機制。
//        return new RoundRobinRule(); //roundRobin方式輪詢選擇server
//        return new RandomRule(); //隨機選擇一個server
//        return new ZoneAvoidanceRule(); //複合判斷server所在區域的性能和server的可用性選擇server
        return new AvailabilityFilteringRule();
    }
}

觸發配置

@EnableZuulProxy
@EnableHystrix
@SpringCloudApplication
@RibbonClients(defaultConfiguration = {RibbonConfiguration.class})
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

發佈了15 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章