六、微服务框架spring cloud组件之容错保护器hystr

2019-04-08  本文已影响0人  小manong

1、通过客户端库对延迟和故障进行保护和控制
2、在一个复杂的分布式系统中停止级联故障
3、快速失败和快速恢复
4、在合理情况下面
5、开启近实时监控、告警和操作控制

一、hystrix简单使用

1、搭建注册中心和服务提供者

(1)搭建eureka注册中心
server-url=http://localhost:8081/eureka/
(2)搭建eureka服务提供中心

 @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        int randomInt = new Random().nextInt(10);
        if (randomInt > 5) {
            try {
                //阻塞3秒,hystrix默认超时是2秒
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "hello " + name;
    }

2、搭建服务消费中心(使用feign)

(1)导入包

<!-- 断路器-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

(2)定义一个调用服务并配置

public class HystrixService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加回调
     * @return
     */
    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloHystrix(){
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:8082/hello/qiu", String.class);
        return forEntity.getBody();
    }

    public String helloFallback(){
        return "error";
    }
}
@Configuration
public class HystrixServiceConfig {
    @Bean
    public HystrixService hystrixService(){
        return new HystrixService();
    }
}

(3)创建controller并访问

@Autowired
    private HystrixService hystrixService;
    @RequestMapping("/hystrix")
    public String hystrix() {
        return hystrixService.helloHystrix();
    }

(4)开启hystrix

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class RibbonConsumer1Application {
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumer1Application.class, args);
    }
}

(5)配置

server.port=8083
spring.application.name=hystrix-consumer
#向注册中心注册并获取相关的服务提供者信息
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/

(6)测试

二、hystrix功能与设计原则

1、hystrix异常机制

(1)failure:执行失败,抛出异常
(2)timeout:执行超时
(3)short_circruited:断路器打开
(4)thread_pool_rejected:线程池拒绝
(5)sempahore_rejected:信号量拒绝

2、hystrix设计原则

(1)防止任何单个依赖项用尽所有容器(例如Tomcat)的用户线程。
(2)提供快速失败机制代替排队
(3)在可行的情况下提供回退以保护用户免于失败(提供了可降级措施)
(4)使用隔离技术(例如隔板,泳道和断路器模式)来限制任何一个依赖项的影响。
(5)通过近实时指标,监控和警报优化发现时间
(6)通过Hystrix的大多数方面的配置更改的低延迟传播和对动态属性更改的支持来优化恢复时间,这允许您使用低延迟反馈循环进行实时操作修改。
(7)防止整个依赖关系客户端执行中的故障,而不仅仅是网络流量。

3、hystrix提供的功能

(1)将所有对外部系统(或“依赖项”)的调用包含在HystrixCommand或HystrixObservableCommand对象中,该对象通常在单独的线程中执行(这是命令模式的一个示例)。
(2)有一个默认值阈值,但对于大多数依赖项,您可以通过“属性”自定义设置这些超时。
(3)为每个依赖项维护一个小的线程池(或信号量); 如果它变满,将立即拒绝发往该依赖项的请求而不是排队。
(4)测量成功,失败(客户端引发的异常),超时和线程拒绝次数。
(5)如果服务的错误百分比超过阈值,则手动或自动地使断路器跳闸以停止对特定服务的所有请求一段时间。
(6)当请求失败时执行回退逻辑,被拒绝,超时或短路。
(7)近乎实时地监控指标和配置更改。

三、hystrix原理及其其他

参考:https://github.com/Netflix/Hystrix/wiki

上一篇下一篇

猜你喜欢

热点阅读