




Ribbon是客户端(消费者)负载均衡的工具。



Ribbon的POM
org.springframework.cloud spring-cloud-starter-netflix-ribbon
升级最新版本,eureka自带Ribbon的依赖

@LoadBalanced注解给RestTemplate开启负载均衡的能力。
官方文档:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
getForObject/getForEntity方法

测试getForEntity方法
@GetMapping("/consumer/payment/getForEntity/{id}")public CommonResult getPayment2(@PathVariable("id") Long id){ResponseEntity entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);if (entity.getStatusCode().is2xxSuccessful()){return entity.getBody();}else {return new CommonResult<>(444,"操作失败");}}
重启测试

IRule:根据特定的算法从服务列表中选取一个要访问的服务。
IRule接口的实现:

负载均衡常用规则:默认为RoundRobinRule轮询。

替换规则

Ribbon的自定义配置类不可以放在@ComponentScan所扫描的当前包下以及子包下,否则这个自定义配置类就会被所有的Ribbon客户端共享,达不到为指定的Ribbon定制配置,而@SpringBootApplication注解里就有@ComponentScan注解,所以不可以放在主启动类所在的包下。(因为Ribbon是客户端(消费者)这边的,所以Ribbon的自定义配置类是在客户端(消费者)添加,不需要在提供者或注册中心添加)

@Configuration
public class MySelfRule {@Beanpublic IRule myRule(){// 随机return new RandomRule();}
}
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class),告诉服务用那种负载模式@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {public static void main(String[] args) {SpringApplication.run(OrderMain80.class);}
}
http://localhost/consumer/payment/get/1,多次刷新实现负载均衡为随机。
public Server choose(ILoadBalancer lb, Object key) {if (lb == null) {log.warn("no load balancer");return null;}Server server = null;int count = 0;while (server == null && count++ < 10) {List reachableServers = lb.getReachableServers();List allServers = lb.getAllServers();int upCount = reachableServers.size();int serverCount = allServers.size();if ((upCount == 0) || (serverCount == 0)) {log.warn("No up servers available from load balancer: " + lb);return null;}int nextServerIndex = incrementAndGetModulo(serverCount);server = allServers.get(nextServerIndex);if (server == null) {/* Transient. */Thread.yield();continue;}if (server.isAlive() && (server.isReadyToServe())) {return (server);}// Next.server = null;}if (count >= 10) {log.warn("No available alive servers after 10 tries from load balancer: "+ lb);}return server;}/*** Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.** @param modulo The modulo to bound the value of the counter.* @return The next value.*/private int incrementAndGetModulo(int modulo) {for (;;) {int current = nextServerCyclicCounter.get();int next = (current + 1) % modulo;if (nextServerCyclicCounter.compareAndSet(current, next))return next;}}
@GetMapping(value = "/payment/lb")public String getPaymentLB(){return serverPort;}
3.80订单微服务改造
public interface ILoadBalancer {//传入具体实例的集合,返回选中的实例ServiceInstance instance(List serviceInstances);
}
@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));System.out.println("******第几次访问,next: "+next);return next;}@Overridepublic ServiceInstance instance(List serviceInstances) {int index = getAndIncrement() % serviceInstances.size();return serviceInstances.get(index);}
}
@Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@GetMapping("/consumer/payment/lb")public String getPaymentLB() {List instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");if (instances == null || instances.size() <= 0){return null;}ServiceInstance serviceInstance = loadBalancer.instance(instances);URI uri = serviceInstance.getUri();return restTemplate.getForObject(uri+"/payment/lb",String.class);}
官网文档:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign

Feign是一个声明式的web服务客户端,让编写web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可。

OpenFeign和Feign的区别

OpenFeign使用在客户端(消费测)


org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-eureka-client com.zhao.springcloud cloud-api-commons 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test
server:port: 80 eureka:client:register-with-eureka: falseservice-url:defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
@SpringBootApplication
// 激活开启feign
@EnableFeignClients
public class OrderFeign {public static void main(String[] args) {SpringApplication.run(OrderFeign.class);}
}
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {@GetMapping("/payment/get/{id}")public CommonResult getPaymentById(@PathVariable("id") Long id);
}
@RestController
@Slf4j
public class OrderFeignController {@Resourceprivate PaymentFeignService paymentFeignService;@GetMapping("/consumer/payment/get/{id}")public CommonResult getPaymentById(@PathVariable("id") Long id){return paymentFeignService.getPaymentById(id);}
}
7.启动测试
自带负载均衡功能



提供者在处理服务时用了3秒,提供者认为花3秒是正常,而消费者只愿意等1秒,1秒后,提供者会没返回数据,消费者就会造成超时调用报错。所以需要双方约定好时间,不使用默认的。
模拟超时出错的情况

@GetMapping("/payment/feign/timeout")public String paymentFeignTimeout(){try{TimeUnit.SECONDS.sleep(3);}catch (InterruptedException e){e.printStackTrace();}return serverPort;}
@GetMapping("/payment/feign/timeout")public String paymentFeignTimeout();
@GetMapping("/consumer/payment/feign/timeout")public String paymentFeignTimeout(){//openFeign-ribbon,客户端一般默认等待1秒return paymentFeignService.paymentFeignTimeout();}


#没提示不管它,可以设置
ribbon:#指的是建立连接后从服务器读取到可用资源所用的时间ReadTimeout: 5000#指的是建立连接使用的时间,适用于网络状况正常的情况下,两端连接所用的时间ConnectTimeout: 5000

概述

打印级别

设置步骤
@Configuration
public class FeignConfig {@BeanLogger.Level feignLogLevel(){return Logger.Level.FULL;}
}
logging:level:#feign日志以什么级别监控哪个接口com.zhao.springcloud.service.PaymentFeignService: debug

