基于gateway的ribbon负载均衡

本文介绍如何使用Spring Cloud Gateway进行路由配置,并结合Hystrix实现服务熔断,防止雪崩效应。涵盖依赖包引入、YAML配置详情、自定义负载均衡策略等关键信息。
网关的包
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
熔断的包,防止雪崩
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
yml里面配置:
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 10
  application:
    name: iem-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      routes:
        - id: iem-resource
          uri: lb://iem-resource
          predicates:
            - Path=/resource-api/**
          filters:
            - StripPrefix=1
            - name: Hystrix
              args:
                name: fallbackcmd
                fallbackUri: forward:/fallBackResource


一个应用启动多次,9009,8001端口,riboon负载均衡

my-load-balanced-service:
  ribbon:
    listOfServers: localhost:9009,localhost:8001
    NFLoadBalancerRuleClassName: com.brt.iem.gateway.auth.blance.MyLoadBalancerRule
    #com.netflix.loadbalancer.RoundRobinRule

MyLoadBalancerRule均衡策略可以自己写

package com.brt.iem.gateway.auth.blance.MyLoadBalancerRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.ArrayList;
import java.util.List;

/**
 * peiyajie 20200824
 */
public class MyLoadBalancerRule extends  AbstractLoadBalancerRule {

    private volatile int total;

    private volatile int index;

    List<Server> upList=new ArrayList<Server>();

    public Server choose(ILoadBalancer lb,Object key){
       if(lb==null){
           return null;
       }else{
           Server server=null;
           while(server==null){
               if(Thread.interrupted()){
                   return null;
               }
               List<Server>  allList=lb.getAllServers();
               int serverCount =allList.size();
               if(serverCount==0){
                   return null;
               }

               if(total==0){
                   upList=lb.getReachableServers();
               }

               if(total<3){
                   if(upList.size()!=lb.getReachableServers().size()){
                       index=0;
                   }
                   server=lb.getReachableServers().get(index);
                   total++;
               }else{
                   total=0;
                   index++;
                   if(index>=lb.getReachableServers().size()){
                       index=0;
                   }
               }

               if(server==null){
                   Thread.yield();
               }else{
                   if(server.isAlive()){
                       return server;
                   }
                   server=null;
                   Thread.yield();
               }
           }//server=null的判断
           return server;
       }
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(),key);
    }
}

参考:https://blog.youkuaiyun.com/u014704612/article/details/105028834/

 

### 原理 APIG(API Gateway,API网关)依赖Ribbon实现负载均衡的原理基于客户端负载均衡机制。Ribbon是Netflix开源的客户端负载均衡器,当APIG接收到客户端的请求时,会根据请求的服务名向服务注册中心(如Eureka)查询该服务的所有可用实例信息。Ribbon会从这些实例列表中,依据特定的负载均衡算法(如轮询、随机等)选择一个合适的服务实例来处理客户端的请求。这样,APIG就能够将请求均匀地分发到多个服务实例上,从而实现负载均衡,提高系统的可用性和性能。 ### 配置 以下是在Spring Cloud环境下,APIG依赖Ribbon实现负载均衡的基本配置步骤: 1. **添加依赖**:在`pom.xml`文件中添加Ribbon和APIG(通常使用Spring Cloud Gateway)的相关依赖。 ```xml <dependencies> <!-- Spring Cloud Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- Ribbon --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <!-- Eureka Client(如果使用Eureka作为服务注册中心) --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> ``` 2. **配置APIG**:在`application.yml`或`application.properties`文件中配置APIG的路由规则和Ribbon相关参数。 ```yaml spring: cloud: gateway: routes: - id: service_route uri: lb://your-service-name # 使用lb://前缀表示使用Ribbon进行负载均衡 predicates: - Path=/your-service-path/** ``` 3. **配置Ribbon**:可以通过配置文件或Java代码来定制Ribbon负载均衡策略。 ```yaml your-service-name: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 使用随机负载均衡策略 ``` ### 使用方法 1. **启动服务注册中心**:如Eureka,确保服务实例能够注册到注册中心。 2. **启动服务提供者**:将服务实例注册到服务注册中心。 3. **启动APIG**:APIG会自动从服务注册中心获取服务实例信息,并使用Ribbon进行负载均衡。 4. **客户端请求**:客户端向APIG发送请求,APIG会根据配置的路由规则和Ribbon负载均衡策略将请求转发到合适的服务实例。 ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @RestController public class GatewayController { private final WebClient webClient; public GatewayController(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl("lb://your-service-name").build(); } @GetMapping("/proxy") public Mono<String> proxyRequest() { return webClient.get().uri("/your-service-path").retrieve().bodyToMono(String.class); } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值