SpringCloud 客戶端負載均衡:Ribbon

Ribbon 介紹

Ribbon 是 Netflix 提供的一個基於 Http 和 TCP 的客戶端負載均衡工具,且已集成在 Eureka 依賴中。

image

1)客戶端負載均衡:

  • image

  • 負載均衡演算法在客戶端

  • 客戶端維護服務地址列表

2)服務端負載均衡:

  • image
  • 負載均衡演算法在服務端
  • 由負載均衡器維護服務地址列表

開啟客戶端負載均衡,簡化 RestTemplate 調用

1)在服務調用者的 RestTemplate 配置類上添加註解:

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced  // 開啟客戶端負載均衡(默認輪詢策略)
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2)在調用時指定服務名:

package com.controller;

import com.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 服務調用方
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/goods/{id}")
    public Goods findOrderByGoodsId(@PathVariable("id") int id) {

        String url = String.format("//eureka-provider/goods/findOne/%d", id);
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;
    }
}

負載均衡策略

負載均衡策略:

  • 輪詢(默認)
  • 隨機
  • 最小並發
  • 過濾
  • 響應時間
  • 輪詢重試
  • 性能可用性

使用負載均衡:

方式一:使用 bean 的方式

  • 在消費者端配置負載均衡策略 Bean:
package com.config;

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

public class MyRule {

    @Bean
    public IRule rule() {
        return new RandomRule();  // 隨機策略
    }

}
  • 在啟動類添加註解:
package com;

import com.config.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

@EnableDiscoveryClient  // 激活DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name="eureka-provider", configuration= MyRule.class)  // 指定服務提供方並配置負載均衡策略
public class ConsumerApp {

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

方式二:使用配置文件

server:
  port: 9000

eureka:
  instance:
    hostname: localhost
  client:
    service-url:
      defaultZone:  //localhost:8761/eureka

spring:
  application:
    name: eureka-consumer

# 設置 Ribbon 的負載均衡策略:隨機策略
EUREKA-PROVIDER:
  ribbon:
    NFloadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule.RandomRule