本篇内容介绍了“怎么理解Spring Cloud的负载均衡策略+重试机制+Hystrix 熔断器”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
负载均衡策略 初体验:
步骤一:修改pom文件,修改服务调用方的pom文件,添加test依赖
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
步骤二:编写测试类,在服务调用方编写Junit测试类
package com.czxy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest(classes=Client4Application.class) //Junit和Spring boot整合,将所有实例加载到spring容器。
@RunWith(SpringRunner.class) //JUnit和Spring整合,将spring容器中的数据注入当前类
public class TestRibbon {
@Resource
private RibbonLoadBalancerClient client;
@Test
public void testDemo(){
// 通过“服务名”获得对应服务实例
for (int i = 0; i < 10; i++) {
ServiceInstance instance = client.choose("service4");
System.out.println(instance.getHost() + ":">
步骤三:修改提供方yml文件,支持显示IP地址,并重启8081和8082
#服务名
spring:
application:
name: service4
#注册地址
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
instance:
prefer-ip-address: true #显示IP地址
修改策略
给指定的“服务”设置策略
服务名.ribbon.NFLoadBalancerRuleClassName=策略实现类
service4:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机
#NFLoadBalancerRuleClassName : com.netflix.loadbalancer.BestAvailableRule #并发最少
#NFLoadBalancerRuleClassName : com.netflix.loadbalancer.WeightedResponseTimeRule #请求时间权重
重试机制
重试机制:服务B访问集群环境下的服务A,某一个服务A宕机,服务B将尝试访问其他可以使用的服务A。
9090访问 8081和8082
如果8082宕机了
9090将尝试访问8081
步骤一:修改pom文件,添加重试retry依赖
<!--重试机制-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
步骤二:修改yml文件,开启cloud重试机制
spring:
cloud:
loadbalancer:
retry:
enabled: true #开启重试机制
步骤三:修改yml文件,配置当前服务的重试参数
service4:
ribbon:
ConnectTimeout: 250 # Ribbon的连接超时时间
ReadTimeout: 1000 # Ribbon的数据读取超时时间
OkToRetryOnAllOperations: true # 是否对所有操作都进行重试
MaxAutoRetriesNextServer: 1 # 切换实例的重试次数
MaxAutoRetries: 1 # 对当前实例的重试次数
Hystix熔断器
Hystrix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。
Hystrix 入门
步骤一:修改pom,添加熔断器依赖
步骤二:修改启动类,添加开启熔断器注解 @EnableHystrix
步骤三:改造dao,远程调用添加 熔断器的备选方案,添加注解 + 备用方法
步骤四:改变服务提供方法,添加线程sleep,0~2000随机 (测试方便)
步骤一:修改pom,添加熔断器依赖
<!--熔断器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
步骤二:修改启动类,添加开启熔断器注解 @EnableHystrix
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix //开启熔断器
public class Client4Application {
public static void main(String[] args) {
SpringApplication.run(Client4Application.class,args);
}
}
步骤三:改造dao,远程调用添加 熔断器的备选方案,添加注解 + 备用方法
package com.czxy.dao;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@Component
public class DataDao {
@Resource
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "dataFallback")
public ResponseEntity<String> data(){
String url = "http://service4/test";
return restTemplate.getForEntity(url,String.class);
}
/**
* 熔断器超时处理方法
* @return
*/
public ResponseEntity<String> dataFallback(){
return ResponseEntity.ok("临时数据");
}
}
步骤四:改变服务提供方法,添加线程sleep,0~~2000随机 (测试方便)
package com.czxy.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping
public ResponseEntity<String> test(HttpServletRequest request) throws Exception {
//模拟延迟
Thread.sleep(new Random().nextInt(2000));
return ResponseEntity.ok("测试数据" + request.getServerPort());
}
}
步骤五:优化dao,打印耗时时间
package com.czxy.dao;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@Component
public class DataDao {
@Resource
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "dataFallback")
public ResponseEntity<String> data(){
//1 记录开始时间
long start = System.currentTimeMillis();
//2 调用
String url = "http://service4/test";
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
//3 记录结束时间
long end = System.currentTimeMillis();
//4 统计耗时
System.out.println("耗时时间:" + (end - start));
return entity;
}
/**
* 熔断器超时处理方法
* @return
*/
public ResponseEntity<String> dataFallback(){
return ResponseEntity.ok("临时数据");
}
}
(面试题)如果项目中同时使用熔断器和Ribbon重试机制,谁先执行?
如果时间不相同,超时时间小的,先执行。
如果时间相同,只执行熔断器
结论:如果两个都需要配置,重试机制的超时时间 小于 熔断器
“怎么理解Spring Cloud的负载均衡策略+重试机制+Hystrix 熔断器”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4234912/blog/3145447