SpringCloud学习记录 | 第八篇:Hystrix服务降级

分布式体系结构面临的问题

复杂的分布式体系结构中的应用程序有多个依赖关系,某些依赖在某些时候不可避免出现失败,出现服务雪崩问题。

断路器

当某个服务单元出现问题之后,通过断路器的故障监控向调用方返回一个预期的、可处理的预备响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常。这样保证服务调用方的线程不会长时间的占用,从而避免了故障在分布式系统中蔓延,乃至雪崩,增加分布式系统的弹性。

构建工程,演示高并发

1.在服务中创建两个方法,一个正常方法另一个模拟耗时操作:

@Service
public class HystrixPaymentService {

    /**
     * 正常方法
     *
     * @param id
     * @return
     */
    public String paymentOK(Integer id) {
        return "线程名:"+Thread.currentThread().getName() + ";paymentOk" + ",id:" + id;
    }

    /**
     * 演示耗时方法
     *
     * @param id
     * @return
     */
    public String paymentTimeOut(Integer id) {
        Integer time=3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程名:"+Thread.currentThread().getName() + ";paymentTimeOut" + ",id:" + id;
    }

}

2.访问两个方法,看他们分别耗时:

2.1 正常方法(paymentOK)耗时:7.36ms

2.2 压测(JMter启动200个线程循环100次调用耗时方法[paymentTimeOut])后的正常方法耗时:1.08s

2.2.1 JMter压测

2.2.2 压测后的正常方法耗时

2.3 当耗时服务被大量请求的时候会影响到正常的服务。

Hystrix登场

1.我们将服务提供者加上Hystrix的服务降级:

(之前说过一个组件的启用基本要历经:引入依赖、开启、使用等几个步骤)

1.1 引入Hystrix依赖(pom.xml中引入Hystrix依赖):

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

1.2 启用Hystrix(主启动类上添加启动注解):

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix  //启用Hystrix
public class OrderHystrixMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderHystrixMain80.class,args);
    }
}

1.3 使用Hystrix服务降级(FallBack):

  /**
     * 演示耗时方法
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentTimeOutFallBackHandler",commandProperties ={
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000")
    } )
    public String paymentTimeOut(Integer id) {
        Integer time=5;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程名:"+Thread.currentThread().getName() + ";paymentTimeOut" + ",id:" + id;
    }

    public String paymentTimeOutFallBackHandler(Integer id){
        return "线程名:"+Thread.currentThread().getName() + ";paymentTimeOutFallBackHandler" + ",id:" + id;
    }

我们在模拟耗时操作的方法上添加@HystrixCommoned注解,其中fallbackMethod属性是说备注的方法在某些条件下所回调的方法,而这里的条件就是@HystrixProperty。这里@HystrixProperty意思就是说这个模拟耗时接口访问超过4s钟的时候就会回调paymentTimeOutFallBackHandler方法返回,从而起到服务降级的效果。具体@HystrixCommoned更多的使用可以参考(jar包Hystrix-core中的HystrixCommandProperties抽象类)下图:

使用方法:https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration

1.4 添加Hystrix调用结果:

1.5 添加全局默认的方法降级:

1.5.1 在service类上增加默认的降级方法:

@DefaultProperties(defaultFallback ="paymentGlobalFallBackMethod")

实现paymentGlobalFallBackMethod方法:

  public String paymentGlobalFallBackMethod() {
        return "线程名:" + Thread.currentThread().getName() + ";paymentGlobalFallBackMethod";
    }

在需要降级的方法上添加@HystrixCommand注解:

@HystrixCommand
public String paymentOK(Integer id) {
    int i=10/0;
    return "线程名:" + Thread.currentThread().getName() + ";paymentOk" + ",id:" + id;
}

这里全局的降级和单个具体的降级处理不冲突,有限使用方法上自己实现的降级方法。

2.结合OpenFeign在客户端做全局服务降级处理

2.1 创建工程:cloud-consume-hystrix-rorder80,引入OpenFeign、Hystrix等组件,记得在主启动类上开启组件:

@SpringBootApplication
@EnableFeignClients //开启OpenFeign
@EnableHystrix //开启Hystrix
public class OrderHystrixMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderHystrixMain80.class,args);
    }
}

2.2 创建OpenFeign调用的接口,添加调用服务的事例名称和fallBack(需要实现该接口):

@FeignClient(name = "CLOUD-PAYMENT-HYSTRIX-SERVICE" ,fallback = PaymentHystrixFallBack.class)
public interface IPaymentHystrixService {

    @GetMapping("/payment/hystrix/payment/ok/{id}")
    String paymentInfoOK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/payment/timeout/{id}")
    String paymentInfoTimeOut(@PathVariable("id") Integer id);

}

IPaymentHystrixService接口实现就是PaymentHystrixFallBack:

@Component
public class PaymentHystrixFallBack implements IPaymentHystrixService {
    @Override
    public String paymentInfoOK(Integer id) {
        return "PaymentHystrixFallBack--paymentInfoOK--id:"+id;
    }

    @Override
    public String paymentInfoTimeOut(Integer id) {
        return "PaymentHystrixFallBack--paymentInfoTimeOut--id:"+id;
    }
}

这样,在服务端遇到异常(运行时、超时、宕机等等异常)客户端都会进入对应的降级方法

其他

1.参考代码:https://github.com/TianLuhua/springCloud2020.git

1.1 服务端 cloud-provider-hystrix-payment8001

1.2 客户端cloud-consume-hystrix-rorder80

1.3 注册中心 cloud-eureka-server7001和cloud-eureka-server7002

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值