Ribbon(瑞本)客户端负载均衡
Ribbon 概述
- Ribbon是 Netflix 提供的一个基于HTTP和TCP的客户端负载均衡工具。
- Ribbon主要有两个功能:
1 简化远程调用
2 负载均衡
服务端负载均衡
负载均衡算法在服务端
由负载均衡器维护服务地址列表
客户端负载均衡
负载均衡算法在客户端
客户端维护服务地址列表
Ribbon 远程调用
Ribbon 可以与 简化 RestTemplate 的远程调用
在e
/**
* 使用Ribbon 简化restTemplate调用过程
* 1 在声明restTemplate的bean的时候,添加一个注解:@LoadBaLanced
* 2 在使用restTemplate发起请求时定义URL时,host:port 可以替换为服务提供方的应用名称
* @param id
* @return
*/
@GetMapping("/goods2/{id}")
public Goods findGoodsById2(@PathVariable("id") int id){
System.out.println("findGoodsById..."+id);
//3 调用方法
String url = "http://EUREKA-PROVIDER/goods/findOne/"+id;
Goods goods = restTemplate.getForObject(url, Goods.class);
return goods;
}
package com.itheima.consumer.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Ribbon 负责均衡策略:
- 随机 :RandomRule
- 轮询 :RoundRobinRule
- 最小并发:BestAvailableRule
- 过滤:AvailabilityFilteringRule
- 响应时间:WeightedResponseTimeRule
- 轮询重试:RetryRule
- 性能可用性:ZoneAvoidanceRule
设置负载均衡策略- 编码
- 配置
user-service: # 生产者服务名称
ribbon: NFloadBalancerRuleClassName: XxxRule # 负载均衡策略类
1 编码模式
package com.itheima.consumer.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
public class MyRule {
/**
* 所有负载均衡的策略
*/
@Bean
public IRule rule(){
return new RandomRule();
}
}
package com.itheima.consumer;
import com.itheima.consumer.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;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient /// 激活DiscoveryClient
/*
配置Ribbon的负载均衡策略
name:设置服务提供方应用名称
configuration: 设置负载均衡的bean
*/
@RibbonClient(name = "EUREKA-PROVIDER",configuration = MyRule.class)
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}