(第五篇)spring cloud之Ribbon负载均衡
目录
一、介绍
1、介绍
2、本地负载和服务器负载
3、RestTemplate的使用
二、核心组件IRule
1、介绍
2、修改cloud-consumer-order80工程
三、自定义负载均衡算法
1、原理
2、自定义算法
一、介绍
1、介绍
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等;Ribbon目前也进入维护模式。
2、本地负载和服务器负载
Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。负载均衡是由服务端实现的。
Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册服务列表,之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。
Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他请求的客户端结合使用,和eureka结合只是其中的一个实例。
3、RestTemplate的使用
RestTemplate 是Spring框架提供的一个用于发起HTTP请求的同步客户端工具,它简化了与http服务的通信过程,并遵循RESTful原则。在Spring Boot项目中,可以通过注入RestTemplate来使用,或者进行一些简单的配置来满足特定需求。
官网https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
一些get方法:
<T> T getForObject(String url, Class<T> responseType, Object... uriVariables);
<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables);
<T> T getForObject(URI url, Class<T> responseType);
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables);
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables);
<T> ResponseEntity<T> getForEntity(URI var1, Class<T> responseType);
一些post方法:
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType);
例如:简单配置
@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory) {return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(15000); // 设置读取超时时间factory.setConnectTimeout(15000); // 设置连接超时时间return factory;}
}
Get使用:
// 发起GET请求并将响应映射到TempUser对象
TempUser result = restTemplate.getForObject("http://localhost:8080/getUser?userName=张三&age=18", TempUser.class);// 使用参数映射
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userName", "张三");
paramMap.put("age", 18);
TempUser result = restTemplate.getForObject("http://localhost:8080/getUser?userName={userName}&age={age}", TempUser.class, paramMap);
Post使用:
// 发起POST请求并获取响应
TempUser param = new TempUser();
param.setUserName("张三");
param.setAge(18);
TempUser result = restTemplate.postForObject("http://localhost:8080/getPostUser", param, TempUser.class);// 发送带有请求头的POST请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<TempUser> httpEntity = new HttpEntity<>(param, headers);
TempUser result = restTemplate.postForObject("http://localhost:8080/getPostUser", httpEntity, TempUser.class);
二、核心组件IRule
1、介绍
IRule:根据特定算法从服务列表中选取一个要访问的服务
- com.netflix.loadbalancer.RoundRobinRule:轮询
- WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
- com.netflix.loadbalancer.RandomRule:随机
- com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
- BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
- AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例
- ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器
2、修改cloud-consumer-order80工程
(1)注意点
官方文档明确给出了警告:这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了
(2)新建MySelfRule
package com.hk.myrule;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 MySelfRule
{@Beanpublic IRule myRule(){return new RandomRule();//定义为随机}
}
(3)修改启动类
package com.hk.cloudstudy;import com.hk.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class MainApp80 {public static void main(String[] args) {SpringApplication.run(MainApp80.class,args);}
}
(4)测试
启动7001,8001和8002,在启动80
访问GET http://localhost:80/consumer/payment/get/1
发现打印的端口是随机出现的
三、自定义负载均衡算法
1、原理
负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 ,每次服务重启动后rest接口计数从1开始。
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
如: List [0] instances = 127.0.0.1:8002
List [1] instances = 127.0.0.1:8001
8001+ 8002 组合成为集群,它们共计2台机器,集群总数为2, 按照轮询算法原理:
当总请求数为1时: 1 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位2时: 2 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
当总请求数位3时: 3 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位4时: 4 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
如此类推......
2、自定义算法
(1)修改80服务,
ApplicationContextBean去掉注解@LoadBalanced
package com.hk.cloudstudy.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 ApplicationContextConfig {//使用@LoadBalanced注解赋予RestTemplate负载均衡的能力@Bean
// @LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}
}
(2)创建LoadBalancer接口
package com.hk.cloudstudy.mylb;import org.springframework.cloud.client.ServiceInstance;import java.util.List;public interface LoadBalancer {ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
(3)创建接口的实现
package com.hk.cloudstudy.mylb;import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;@Component
public class MyLB implements LoadBalancer {private AtomicInteger atomicInteger = new AtomicInteger(0);public final int getAndIncrement(){int current;int next;do{current = this.atomicInteger.get();next = current >= 2147483647 ? 0 : current + 1;} while(!this.atomicInteger.compareAndSet(current,next));return next;}@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances) {// rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标int index = getAndIncrement() % serviceInstances.size();return serviceInstances.get(index);}
}
(4)修改controller
package com.hk.cloudstudy.controller;import com.hk.cloudstudy.entities.CommonResult;
import com.hk.cloudstudy.entities.Payment;
import com.hk.cloudstudy.mylb.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import java.net.URI;
import java.util.List;@RestController
public class OrderController {// public static final String PAYMENT_URL = "http://localhost:8001";public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; // CLOUD-PAYMENT-SERVICE注册中心的服务名称@Autowiredprivate RestTemplate restTemplate;//可以获取注册中心上的服务列表@Autowiredprivate DiscoveryClient discoveryClient;@Autowiredprivate LoadBalancer loadBalancer;@GetMapping("/consumer/payment/{id}")public String getPaymentLB(){List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");if (instances == null || instances.size() <= 0){return null;}ServiceInstance serviceInstance = loadBalancer.instances(instances);URI uri = serviceInstance.getUri();return restTemplate.getForObject(uri + "/payment/lb", String.class);}//客户端用浏览器是get请求,但是底层实质发送post调用服务端8001@GetMapping("/consumer/payment/create")public CommonResult create(Payment payment){return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);}@GetMapping("/consumer/payment/get/{id}")public CommonResult getPaymentById(@PathVariable("id") Long id){return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class, id);}}
(5)8001和8002修改controller
@GetMapping(value = "/payment/lb")public String getPaymentLB(){return serverPort;}
(6)测试
启动7001,8001和8002, 启动80
访问:http://localhost/consumer/payment/lb
发现8001和8002交替出现