SpringCloud之微服务容错
来源:卿亦离     阅读:527
源码超市
发布于 2019-06-11 03:31
查看主页

1.雪崩效应

雪崩效应

??如上图所示,假设我们有3个微服务A,B,C,A调用B,B调用C,假如C挂掉了,因为B是同步调用,不断等待,导致资源耗尽,B也挂掉,接下来A也挂掉了,造成了雪崩效应!为了防止雪崩效应,所以我们要在本篇文章中详情Hystrix。

2.Hystrix

Hystrix

??hystrix对应的中文名字是“豪猪”,豪猪周身长满了刺,能保护自己不受天敌的伤害,代表了一种防御机制,反正这种猪我是没吃过的,不敢吃。那么Hystrix又具有什么样的特点呢:

2.1服务降级

??双11的时候我们经常看到哎哟被挤爆了,这其实就是一种服务降级。那么Hystrix是怎样做到服务降级的呢?

2.1.1优先核心服务,非核心服务不可用或者者弱可用

??比方在一个系统中我们可能有限保证订单和支付服务,但是对于广告之类的服务就若花掉

2.1.2通过HystrixCommand注解

2.1.3fallbackMethod中具体实现降级逻辑

2.1.4具体使用

2.1.4.1pom.xml

        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>        </dependency>

2.1.4.2启动类

//@SpringBootApplication//@EnableDiscoveryClient//@EnableCircuitBreaker@SpringCloudApplicationpublic class OrderApplication {    public static void main(String[] args) {        SpringApplication.run(OrderApplication.class, args);    }}

??在这里我们引入了@EnableCircuitBreaker这个注解,但是可以看到我们的main函数所在的类上面有好多注解了,我们这里用一个SpringCloudApplication注解包含上面的3个注解
2.1.4.3HystrixCommand与fallback的使用

    @HystrixCommand(fallbackMethod="fallback")    @GetMapping("/getProductInfoList")    public String getProductInfoList(@RequestParam("number") Integer number) {        RestTemplate restTemplate = new RestTemplate();        return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",                Arrays.asList("157875196366160022"),                String.class);    }    private String fallback() {        return "太拥挤了, 请稍后再试~~";    }

??假设你的方法有几万个,上面的这种写法用@HystrixCommand这个注解一定要用几万次,太麻烦了,我们来优化和升级一下:

@RestController@DefaultProperties(defaultFallback = "defaultFallback")public class HystrixController {    @HystrixCommand(commandProperties = {            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")    })    @GetMapping("/getProductInfoList")    public String getProductInfoList(@RequestParam("number") Integer number) {        RestTemplate restTemplate = new RestTemplate();        return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",                Arrays.asList("157875196366160022"),                String.class);    }    private String defaultFallback() {        return "默认提醒:太拥挤了, 请稍后再试~~";    }}

??直接在Controller上面写了一个DefaultProperties这样的注解,而后定义了一个defaultFallback这样的方法,我们在getProductInfoList这个方法上的@HystrixCommand注解上可以不在注明fallback方法了,由于我们都用defaultFallback了。但是在这里我们用了一个commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),这个表示当调用方法超过3秒钟时,就服务降级

2.2依赖隔离

??Hystrix使用依赖隔离完成的是线程池的隔离,它为每个HystrixCommand创立一个单独的线程池。这样某个在HystrixCommand包装下的依赖服务出现推迟过高的情况,也只是对该依赖的服务调用产生影响,并不会拖慢其余服务。使用了HystrixCommand将某个函数包装成Hystrix命令时,Hystrix框架就会自动的为这个函数实现了依赖隔离,所以依赖隔离和服务降级是一体化实现的。

2.3服务熔断

??当服务调用发生错误到肯定比例的时候,断路器就会打开,服务的调用会转向另外一个指定的调用方法,这就是服务熔断,这样说比较笼统,我们看看下面这个图:


断路器

??断路器一共有三个状态,初始的时候是closed状态,假如客户不断调用且失败次数达到了肯定的阈值,这个时候断路器就会变成open状态,接下来客户不断调用这个接口都是进入到另一个缺省方法中。但是断路器不会一直处于open状态,当open状态达到肯定时间后,断路器会变成half open状态,进入half open状态后,将会允许请求再次访问真正的服务,假如访问成功了,断路器会变成closed状态,服务恢复正常,假如还失败又再次进入到open状态。

2.3.1代码演示

    @HystrixCommand(commandProperties = {            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),                  //设置熔断            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //请求数达到后才计算            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),   //错误率    })    @GetMapping("/getProductInfoList")    public String getProductInfoList(@RequestParam("number") Integer number) {        if (number % 2 == 0) {            return "success";        }        RestTemplate restTemplate = new RestTemplate();        return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",                Arrays.asList("157875196366160022"),                String.class);    }

??通过代码,我们可以看到,有四个参数,但是最重要的还是这三个参数:
??1.circuitBreaker.requestVolumeThreshold 请求数达到后才计算
??2.circuitBreaker.sleepWindowInMilliseconds open状态达到这个时间后,就会进入到半熔断状态
??3.circuitBreaker.errorThresholdPercentage 失败请求比例

2.3.2使用配置项

??从上面的代码中,我们可以看到,很多配置项都是写在了代码里面,接下来,我们把这些配置放到配置文件里面去:

@HystrixCommand    @GetMapping("/getProductInfoList")    public String getProductInfoList(@RequestParam("number") Integer number) {        if (number % 2 == 0) {            return "success";        }        RestTemplate restTemplate = new RestTemplate();        return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",                Arrays.asList("157875196366160022"),                String.class);    }

在yaml文件中增加这样的配置:

hystrix:  command:    default:      execution:        isolation:          thread:            timeoutInMilliseconds: 1000    getProductInfoList:      execution:        isolation:          thread:            timeoutInMilliseconds: 3000

??在yaml文件中有一个getProductInfoList配置项,和方法名一模一样,还有一个default选项,default选项表示所有被HystrixCommand注解的方法都可以用这个配置,getProductInfoList表示只有这个方法可以用这个配置项。

2.3.3feign-hystrix的使用

??上面的小章节我们使用的是RestTemplate模板,接下来我们使用feign配合hystrix来进行使用,有意思的是大家可以看看spring-cloud-starter-feign的pom.xml其实已经在内部依赖了hystrix。

2.3.3.1yaml配置文件

feign:  hystrix:    enabled: true

2.3.3.2FeignClient

@FeignClient(name = "product", fallback = ProductClient.ProductClientFallback.class)public interface ProductClient {    @PostMapping("/product/listForOrder")    List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);    @PostMapping("/product/decreaseStock")    void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList);    @Component    static class ProductClientFallback implements ProductClient {        @Override        public List<ProductInfoOutput> listForOrder(List<String> productIdList) {            return null;        }        @Override        public void decreaseStock(List<DecreaseStockInput> decreaseStockInputList) {        }    }}

??两个注意点,一个是fallback的配置,还有一个是内部类需要加上@Component注解

2.3.3.3调用方记得加上ComponentScan

2.4监控HystrixDashBoard

2.4.1pom.xml

spring-cloud-starter-hystrix-dashboard

2.4.2yaml文件

management:  context-path: /

2.4.3访问

IP:PORT/hystrix
??服务容错就讲到这里,下一章节我们讲解下服务跟踪。

免责声明:本文为用户发表,不代表网站立场,仅供参考,不构成引导等用途。 系统环境 服务器应用
相关推荐
掌握这些面试题,java面试再也不会频繁被坑了
前台工程师需要理解的进程与线程
一种让工作效率提升2倍的方法
javascript纯小白快速学习指南半年变大神(足以)不行送小姐姐
新手UI设计师必学的UI 交互动效制作准则
首页
搜索
订单
购物车
我的