Spring Cloud Alibaba Nacos 负载均衡策略Ribbon配置

 

 

 ribbon有7种负载均衡策略可供选择:

1、随机策略——RandomRule

2、轮询策略——RoundRobinRule
注:Ribbon默认策略

3、重试策略——RetryRule

4、最低并发策略——BestAvailableRule

5、可用过滤策略——AvailabilityFilteringRule
过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值)

性能仅次于最低并发策略。

6、响应时间加权策略——WeightedResponseTimeRule
每隔30秒计算一次服务器响应时间,以响应时间作为权重,响应时间越短的服务器被选中的概率越大。

7、区域权衡策略——ZoneAvoidanceRule

Ribbon的负载均衡策略使用建议
一般情况下,推荐使用最低并发策略,这个性能比默认的轮询策略高很多。

 
策略类   命名 描述
RandomRule 随机策略 随机选择server
RoundRobinRule 轮询策略 按照顺序选择server(ribbon默认策略)
RetryRule 重试策略 在一个配置时间段内,当选择server不成功,则一直尝试选择一个可用的server
BestAvailableRule 最低并发策略 逐个考察server,如果server断路器打开,则忽略,再选择其中并发链接最低的server
AvailabilityFilteringRule 可用过滤策略 过滤掉一直失败并被标记为circuit tripped的server,过滤掉那些高并发链接的server(active connections超过配置的阈值)
ResponseTimeWeightedRule 响应时间加权重策略 根据server的响应时间分配权重,响应时间越长,权重越低,被选择到的概率也就越低。响应时间越短,权重越高,被选中的概率越高,这个策略很贴切,综合了各种因素,比如:网络,磁盘,io等,都直接影响响应时间
ZoneAvoidanceRule 区域权重策略 综合判断server所在区域的性能,和server的可用性,轮询选择server并且判断一个AWS Zone的运行性能是否可用,剔除不可用的Zone中的所有server

 配置类配置

 

 

package com.wsm.ribbon;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RibbonRandomRuleConfig {

    //方法名一定要中 iRule
    @Bean
    public IRule iRule(){
        return new RandomRule();
    }
}

 

package com.wsm.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/add")
    public String add(){
        System.out.println("aaaaaaaaaaaaa");
//        String msg = restTemplate.getForObject("http://localhost:8011/stock/reduct", String.class);
        String msg = restTemplate.getForObject("http://stock-service/stock/reduct", String.class);
        return "hello world "+msg;
    }
}

 

package com.wsm.order;

import com.wsm.ribbon.RibbonRandomRuleConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
//@EnableDiscoveryClient 老版本要加,新版本可以不加
@RibbonClients(value = {
        @RibbonClient(name = "stock-service",configuration = RibbonRandomRuleConfig.class)
})
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }

    @Bean
    @LoadBalanced //启用负载均衡
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        RestTemplate restTemplate = builder.build();
        return restTemplate;
    }
}

 

server:
  port: 8030
  #应用名称  (nacos 会将该名称当作服务名称)
spring:
  application:
    name: order-ribbon-service
  cloud:
    nacos:
#      server-addr: 127.0.0.1:8848
      server-addr: 192.168.133.128:8847  #集群 nginx 负载均衡访问 nacos
      discovery:
        username: nacos
        password: nacos
        namespace: public

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloudalibaba</artifactId>
        <groupId>com.wsm.springcloud</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order-ribbon</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
<!--            <version>2.5.5</version>-->
        </dependency>

        <!-- nacos 服务注册发现  -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

</project>

 

 

 配置文件配置

server:
  port: 8030
  #应用名称  (nacos 会将该名称当作服务名称)
spring:
  application:
    name: order-ribbon-service
  cloud:
    nacos:
#      server-addr: 127.0.0.1:8848
      server-addr: 192.168.133.128:8847  #集群 nginx 负载均衡访问 nacos
      discovery:
        username: nacos
        password: nacos
        namespace: public
stock-service:
  ribbon:
    NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule  #指定使用Nacos提供的负载均衡策略(优先调用同一集群的实例,基于随机&权重)

 

package com.wsm.order;

import com.wsm.ribbon.RibbonRandomRuleConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
//@EnableDiscoveryClient 老版本要加,新版本可以不加
//@RibbonClients(value = {
//        @RibbonClient(name = "stock-service",configuration = RibbonRandomRuleConfig.class)
//})
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }

    @Bean
    @LoadBalanced //启用负载均衡
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        RestTemplate restTemplate = builder.build();
        return restTemplate;
    }
}

 

 

 自定义负载均衡策略

package com.wsm.ribbon.rule;

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

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class CustomRule extends AbstractLoadBalancerRule {

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        //获得当前请求的服务实例
        List<Server> reachableServers = loadBalancer.getReachableServers();
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
        Server server = reachableServers.get(random);
//        if(server.isAlive()){
//            return server;
//        }
        return server;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}

 

server:
  port: 8030
  #应用名称  (nacos 会将该名称当作服务名称)
spring:
  application:
    name: order-ribbon-service
  cloud:
    nacos:
#      server-addr: 127.0.0.1:8848
      server-addr: 192.168.133.128:8847  #集群 nginx 负载均衡访问 nacos
      discovery:
        username: nacos
        password: nacos
        namespace: public
stock-service:
  ribbon:
#    NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule  #指定使用Nacos提供的负载均衡策略(优先调用同一集群的实例,基于随机&权重)
    NFLoadBalancerRuleClassName: com.wsm.ribbon.rule.CustomRule

 

server:
  port: 8030
  #应用名称  (nacos 会将该名称当作服务名称)
spring:
  application:
    name: order-ribbon-service
  cloud:
    nacos:
#      server-addr: 127.0.0.1:8848
      server-addr: 192.168.133.128:8847  #集群 nginx 负载均衡访问 nacos
      discovery:
        username: nacos
        password: nacos
        namespace: public
stock-service:
  ribbon:
#    NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule  #指定使用Nacos提供的负载均衡策略(优先调用同一集群的实例,基于随机&权重)
    NFLoadBalancerRuleClassName: com.wsm.ribbon.rule.CustomRule
ribbon:
  eager-load:
    enabled: true #开启ribbon饥饿加载
    clients: stock-service  #配置stock-service使用ribbon饥饿加载,多个使用逗号分隔

 

 

 

 

 

 

posted @ 2021-11-02 23:58  残星  阅读(6008)  评论(0编辑  收藏  举报