首页 > 其他分享 >springcloud(四) - 服务治理Hystrix

springcloud(四) - 服务治理Hystrix

时间:2023-02-09 17:24:02浏览次数:42  
标签:降级 Hystrix springcloud public 熔断 治理 熔断器 超时 id

功能介绍

调用下游服务,下游因为超时、异常等原因报错的时候。hystrix保证不会出现整体异常,避免雪崩。主要策略是服务的熔断、降级

 

应用场景

降级:异常、超时、熔断等情况发生后,不让客户端等待返回友好提示

熔断:访问量和失败数量到达设置的数值后,返回友好提示拒绝访问

 

server端降级

<!-- jar包依赖 -->
<!--hystrix-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>


//启动类支持Hystrix
@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
@EnableCircuitBreaker//开启Hystrix
public class PaymentHystrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
}

//方法执行时间超过3秒,则降级处理
    /**
     * 超时访问,演示降级
     * execution.isolation.thread.timeoutInMilliseconds超时阈值设置
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_TimeOut(Integer id) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut,id: " + id + "\t" + "O(∩_∩)O";
    }

    public String paymentInfo_TimeOutHandler(Integer id) {
        return "/(ㄒoㄒ)/调用支付接口超时或异常:\t" + "\t当前线程池名字" + Thread.currentThread().getName();
    }

客户端降级参考:https://blog.csdn.net/qq_41539088/article/details/127681581

 

熔断

熔断的三大参数:

快照时间窗:触发熔断器的周期时间,默认10s

请求总阀值:在快照时间窗内,请求到达某个数量后,才会开启熔断器。假设这个数量设置为20,如果十秒内只发生了19次请求 ,即便都失败了,也不会打开熔断器。

错误百分比阀值:请求错误率到达阀值后,才会开启熔断器。比如10s内发起40次请求,30次失败了,二设置的总阀值为50%,则会开启熔断器。

 

 服务监控hystrixDashboard

 以图片报表的方式展示给用户,每秒执行了多少请求、多少失败等

<!-- 添加依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

<!-- 需要监控的项目 -->
<!-- actuator监控信息完善 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>


//启动类添加监控器支持
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001{
    public static void main(String[] args){
        SpringApplication.run(HystrixDashboardMain9001.class,args);
    }
}

 

标签:降级,Hystrix,springcloud,public,熔断,治理,熔断器,超时,id
From: https://www.cnblogs.com/zhougongjin/p/17106313.html

相关文章