Spring Cloud Alibaba学习02Ribon基本使用

Ribon是Netflix公司开发的负载均衡组件。是一个客户端(服务消费者)负载均衡器,运行在客户端(服务消费者)上。目前已经闭源停止维护。

但目前Spring Cloud Alibaba的负载均衡解决方案,依然使用的是Ribbon。

在引入Nacos之后,可以看到依赖关系。

使用方式:

 1 package com.yas;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 6 import org.springframework.cloud.client.loadbalancer.LoadBalanced;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.web.client.RestTemplate;
 9 
10 @SpringBootApplication
11 @EnableDiscoveryClient
12 public class OrderApp {
13     public static void main(String[] args) {
14         SpringApplication.run(OrderApp.class);
15     }
16 
17     @Bean
18     @LoadBalanced//使用Ribon调用服务,将域名请求变为服务地址请求
19     public RestTemplate initRestTemplate() {
20         return new RestTemplate();
21     }
22 }

Ribbon的工作流程:

1.Ribbon拦截所有的远程调用。

2.解析url中的host,获取servicename。

3.根据servicename获取实例列表(先从本地缓存中获取)。

如果获取到实例列表,通过相应的负载均衡策略,选择一个实例。

如果未能获取到实例列表,则请求nacos-server,将获取到的列表缓存起来。

4.对选定的实例进行调用。

Ribbon的负载均衡策略:

代码实现更改负载均衡策略:

在服务的消费者代码中,加入一个配置文件。(注意不能在Spring Boot的启动类所在的包下)

MyRule代码:

 1 package com.rule;
 2 
 3 import com.netflix.loadbalancer.BestAvailableRule;
 4 import com.netflix.loadbalancer.IRule;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 
 8 @Configuration
 9 public class MyRule {
10     @Bean
11     public IRule getRule(){
12         return new BestAvailableRule();
13     }
14 }

启动类代码修改OrderApp:

 1 package com.yas;
 2 
 3 import com.rule.MyRule;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 7 import org.springframework.cloud.client.loadbalancer.LoadBalanced;
 8 import org.springframework.cloud.netflix.ribbon.RibbonClient;
 9 import org.springframework.context.annotation.Bean;
10 import org.springframework.web.client.RestTemplate;
11 
12 @SpringBootApplication
13 @EnableDiscoveryClient
14 @RibbonClient(name = "cloud-goods",configuration = {MyRule.class})
15 public class OrderApp {
16     public static void main(String[] args) {
17         SpringApplication.run(OrderApp.class);
18     }
19 
20     @Bean
21     @LoadBalanced//使用Ribon调用服务,将域名请求变为服务地址请求
22     public RestTemplate initRestTemplate() {
23         return new RestTemplate();
24     }
25 }
原文地址:https://www.cnblogs.com/asenyang/p/15538641.html