早上刷圈看到 Spring Cloud Hoxton.M2 Released 的消息,隨手發佈到了個人知識星球,過了會有個朋友過來以下問題。 抽取半天時間學習spring-cloud-loadbalancer 的源碼,整理出此文總結
git
Spring Cloud Hoxton.M2 是第一個整合新的loadbalancer實現來替代Ribbon的版本github
Spring Cloud Hoxton.M2 is the first release containing both blocking and non-blocking load balancer client implementations as an alternative to Netflix Ribbon which has entered maintenance mode.
spring-cloud-loadbalancer
替代ribbon,項目託管在<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.M2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencyManagement>
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <exclusions> <exclusion> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </exclusion> </exclusions> </dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-loadbalancer</artifactId> </dependency>
@Configuration public class LbConfiguration { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } } @GetMapping("/demo") public String doOtherStuff() { return restTemplate.getForObject("http://big-provider-server/demo", String.class); }
// 刪除只保留了核心代碼注意 public class BlockingLoadBalancerClient implements LoadBalancerClient { @Override public <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException { // 根據 服務名稱去查詢可用實例 ServiceInstance serviceInstance = choose(serviceId); return execute(serviceId, serviceInstance, request); } @Override public ServiceInstance choose(String serviceId) { // 獲取負載均衡策略 ReactiveLoadBalancer<ServiceInstance> loadBalancer = loadBalancerClientFactory .getInstance(serviceId); // 執行負載均衡策略獲取能夠實例 Response<ServiceInstance> loadBalancerResponse = Mono.from(loadBalancer.choose()) .block(); return loadBalancerResponse.getServer(); } }
public class RoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalancer { public Mono<Response<ServiceInstance>> choose(Request request) { ServiceInstanceSupplier supplier = this.serviceInstanceSupplier.getIfAvailable(); return supplier.get().collectList().map(instances -> { if (instances.isEmpty()) { log.warn("No servers available for service: " + this.serviceId); return new EmptyResponse(); } // TODO: enforce order? int pos = Math.abs(this.position.incrementAndGet()); ServiceInstance instance = instances.get(pos % instances.size()); return new DefaultResponse(instance); }); } }
ZoneAvoidanceRule
複合判斷server所在區域的性能和server的可用性選擇serverspring-cloud-loadbalancer
僅支持 重試操做的配置老老實實用 ribbon
spring
以上源碼 https://github.com/pigxcloud/bigapp
歡迎關注 基於Spring Boot 2.1.七、 Spring Cloud Greenwich.SR二、 OAuth2 的RBAC 權限管理系統負載均衡
歡迎關注咱們得到更多的好玩JavaEE 實踐maven
項目推薦: Spring Cloud 、Spring Security OAuth2的RBAC權限管理系統 歡迎關注ide