SpringCloud H版系列5--Ribbon负载均衡服务调用
Ribbon负载均衡服务调用
- 一、Ribbon
- 二、Ribbon使用
- 三、测试
一、Ribbon
Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。
通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。
Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。
二、Ribbon使用
实现负载均衡的算法。
负载规则替换,注意,不能与主启动类在同一个包下!
2.1 修改cloud-consumer-order80
ribbon默认负载均衡策略是:轮询,这里自定义修改,设置为另一个负载均衡策略:随机
MySelfRule
package com.atguigu.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 {
//ribbon默认负载均衡策略是:轮询,这里自定义修改,设置为另一个负载均衡策略:随机
//通过多次访问http:80//localhost/consumer/payment/get/1,发现随机落在8001和8002服务器
@Bean
public IRule myRule(){
return new RandomRule();//定义为随机
}
}
主启动类OrderMain80
package com.atguigu.springcloud;
import com.atguigu.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 OrderMain80 {
/*先启动7001 *再启动8001 * 然后启动80 * */
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class,args);
}
}
主启动类注释:@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
作用是替换Ribbon负载均衡规则,负载均衡轮询算法 :rest接口第几次请求次数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务器重启后,rest接口计数从1开始。
Ribbon源码
private int incrementAndGetModulo(int modulo) {
int current;
int next;
do {
current = this.nextServerCyclicCounter.get();
next = (current + 1) % modulo;
} while(!this.nextServerCyclicCounter.compareAndSet(current, next));
return next;
}
2.2 手写一个负载的算法CAS+自旋锁
首先8001、8002服务controller层加上
@GetMapping("/payment/lb")
public String getPaymentLB(){
return serverPort;
}
LoadBalancer接口:
package com.atguigu.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalance {
//手写负载均衡算法接口
ServiceInstance instance(List<ServiceInstance> serviceInstances);//把当前服务器实例存入List
}
LoadBalance的实现类MyLB
package com.atguigu.springcloud.lb;
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 LoadBalance {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncrement(){
int current;
int next;
do{
current = this.atomicInteger.get();
next = current >= Integer.MAX_VALUE ? 0 : current+1;//当next下标大于MAX_VALUE时,清零,重写累加
}while (!this.atomicInteger.compareAndSet(current,next));//如果当前值和预期值一致,则this.atomicInteger.compareAndSet(current,next)为true
// !true则为false,跳出do while循环,打印出信息
System.out.println("**********第几次访问,次数next:"+next);
return next;
}
//ribbon负载均衡算法原理:rest接口第几次请求数 % 服务器集群总数 = 实际调用服务器位置下标
//每次重启后,rest接口计数从1开始
@Override
public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement()%serviceInstances.size();
return serviceInstances.get(index);
}
}
OrderController中添加getPaymentLB()方法
package com.atguigu.springcloud.controller;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalance;
import com.atguigu.springcloud.lb.MyLB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
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 javax.annotation.Resource;
import java.net.URI;
import java.util.List;
@RestController
@Slf4j
public class OrderController {
@Autowired
private LoadBalance loadBalance;
@Autowired
private DiscoveryClient discoveryClient;
//public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";//负载均衡
@Resource
private RestTemplate restTemplate;
//使用方式(url,requestMap,responseBean.class)三个参数分别代表rest请求地址、请求参数、http响应转换成的对象类型
//RestTemplate提供了多种便捷访问远程Http服务的方法,
//是一种简单便捷的访问restful服务的模板类,是spring提供的用于访问Rest服务的客户端模板工具集。
//getForObject返回响应体重数据转化成的对象,即json
//getForEntity返回对象是ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
//return restTemplate.postForEntity(PAYMENT_URL+"/payment/create",payment,CommonResult.class).getBody();
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get"+id,CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){ //http请求编码2xx比如200
return entity.getBody();
}else{
return new CommonResult<Payment>(444,"操作失败!");
}
}
@GetMapping("/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0) {
return null;
}
ServiceInstance serviceInstance = loadBalance.instance(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri + "/payment/lb", String.class);
}
}
配置类ApplicationContext
package com.atguigu.springcloud.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 ApplicationContext {
//@Bean 代替了xml方式配置注入Spring
@Bean
@LoadBalanced //手写负载均衡算法,则注释掉
//开启负载均衡注解,轮询查询8001和8002的EurekaClient
public RestTemplate getRestTemplate(){
//RestTemplate提供了多种便捷访问远程http服务的方法
//是一种简单便捷访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具类
return new RestTemplate();
}
}
三、测试
启动7001、7002、8001、8002和80
参考文章
https://blog.csdn.net/weixin\_45821811/article/details/117401512
还没有评论,来说两句吧...