springcloud之Hystrix

本文围绕Spring展开,介绍了服务降级、熔断和限流的概念。新建模块模拟服务器访问缓慢问题,需对服务优化。还阐述了Hystrix服务降级、客户端服务降级、全局服务熔断降级的实现方式,最后提出通过feign客户端进行服务降级是最佳处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念介绍

服务降级: fallback : 例如当服务器繁忙时或者链接超时,不让客户端一直等待并立刻返回一个友好提示
服务熔断:break: 类比于保险丝,当达到最大服务访问时,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示
服务限流:flowlimit: 秒杀等高并发等操作,严禁一窝蜂的拥挤,大家排队,一秒钟N个,有序进行

新建模块

新建模块,故意造成服务器访问返回缓慢的现象

@Service
public class PaymentService {
    /**
     * 正常访问
     * @param id
     * @return
     */
    public String PaymentInfo_ok(Integer id){
        return "线程池: " + Thread.currentThread().getName() + "   PaymentInfo_ok,id:  " + id;
    }

    public String PaymentInfo_Timeout(Integer id){
        int timeNumber = 3;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池: " + Thread.currentThread().getName() + "   PaymentInfo_Timeout,id:  " + id;
    }

}

启动项目,访问ok方法,结果瞬间返回,访问timeout方法,会出现转圈,自测通过,然后使用jmeter开启2w个请求测试,发现ok方法也会出现转圈等待的现象

此时,需要对服务进行优化

Hystrix服务降级

在原来的代码中添加新的注解 @HystrixCommand

@Service
public class PaymentService {
    /**
     * 正常访问
     * @param id
     * @return
     */
    public String PaymentInfo_ok(Integer id){
        return "线程池: " + Thread.currentThread().getName() + "   PaymentInfo_ok,id:  " + id;
    }

    @HystrixCommand(fallbackMethod = "PaymentInfo_PaymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String PaymentInfo_Timeout(Integer id){
        int timeNumber = 5;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池: " + Thread.currentThread().getName() + "   PaymentInfo_Timeout,id:  " + id;
    }

    public String PaymentInfo_PaymentInfo_TimeoutHandler(Integer id){

        return "线程池: " + Thread.currentThread().getName() + "   PaymentInfo_PaymentInfo_TimeoutHandler,id:  " + id + " , 出现异常";

    }

}

并且在启动类上添加新的注解 @EnableCircuitBreaker

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker//服务熔断
public class PaymentHystrixMain8001 {

    public static void main(String[] args) {

        SpringApplication.run(PaymentHystrixMain8001.class,args);

    }

}

运行项目访问 , 出现以下界面
在这里插入图片描述
发现访问的线程池发生了改变,原线程为
在这里插入图片描述

客户端服务降级

服务降级一般是放在客户端,更改客户端代码

在yml配置文件中新增配置

server:
  port: 80
spring:
  application:
    name: cloud-order-consumer
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/

feign:
  hystrix:
    enabled: true #开启hystrix

在启动类中添加注解 @EnableHystrix

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class OrderHystrixMain80 {
    public static void main(String[] args) {

        SpringApplication.run(OrderHystrixMain80.class,args);

    }
}

修改Controller接口

	@GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    })
    public String PaymentInfo_Timeout(@PathVariable Integer id){
        String result = paymentHystrixService.PaymentInfo_Timeout(id);
        return result;
    }
    public String paymentInfo_TimeoutFallback(@PathVariable Integer id){

        return "我是消费者80,对方支付系统繁忙,请稍后再试";
    }

全局服务熔断降级

  1. 首先需要在controller类上新增注解 @DefaultProperties
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {
  1. 编写全局降级处理方法
//全局fallback方法
    public String payment_Global_FallbackMethod(){

        return "Global异常处理信息,请稍后再试";

    }
  1. 在需要全局服务降级的接口中添加注解 @HystrixCommand
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
//    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutFallback",commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
//    })
    @HystrixCommand
    public String PaymentInfo_Timeout(@PathVariable Integer id){
        String result = paymentHystrixService.PaymentInfo_Timeout(id);
        return result;
    }

服务降级最佳处理方式

之前的方法需要在类或者接口方法上添加注解,可以通过feign客户端来进行服务降级

  1. feign客户端代码
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {

    @GetMapping("/payment/hystrix/ok/{id}")
    public String PaymentInfo_ok(@PathVariable(value="id") Integer id);


    @GetMapping("/payment/hystrix/timeout/{id}")

    public String PaymentInfo_Timeout(@PathVariable(value="id") Integer id);


}
  1. 编写一个类实现该接口
@Component
public class PaymentFallbackService implements PaymentHystrixService
{

    @Override
    public String PaymentInfo_ok(Integer id) {
        return "-----------PaymentFallbackService:PaymentInfo_ok fall back";
    }

    @Override
    public String PaymentInfo_Timeout(Integer id) {
        return "-----------PaymentFallbackService:PaymentInfo_Timeout fall back";
    }
}
  1. feign客户端添加注解
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)

无需其它配置,直接启动,也会出现服务降级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值