SpringCloud-Hystrix

Hystrix

1、线程隔离

2、服务降级

​ 当服务提供方出错、或处理超时时给出友好的提示

2.1 服务提供方实现服务降级

  1. 添加pom
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

​ 2、引导类添加注解

@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
@EnableCircuitBreaker
public class ProviderApp {


    public static void main(String[] args) {
        SpringApplication.run(ProviderApp.class,args);
    }
}

​ 3、为方法指定降级方法

    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod ="findOne_fallback",commandProperties =指定超时时间 )
    public Goods findOne(@PathVariable("id") int id){

        //TimeUnit.MICROSECONDS.sleep(750);
        try {
            Thread.sleep(2000); //调用service==>dao===>select * from employee
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Goods goods = goodsService.findOne(id);

        return goods;
    }

    public Goods findOne_fallback(int id){
        return null;
    }

2.2 调用方实现服务降级

由于调用方采用的是Feign,feign自动集成了hystrix,所以不用添加hystrix的座标

1.实现feign接口开发降级处理类

@Component
public class GoodFeignFallBack  implements GoodsFeignClient{
    @Override
    public Goods findOne(int id) {
        return null;
    }
}

2、在feign接口上接定降级处理类

@FeignClient(name="eureka-provider",fallback = GoodFeignFallBack.class)
public interface GoodsFeignClient {

    @GetMapping("/goods/findOne/{id}")
    public Goods findOne(@PathVariable("id") int id);
}

3、在yml中启用hystrix功能

feign:
  hystrix:
    enabled: true

3、熔断

默认情况下hystrix的断路器是关闭的,此时能够正常访问服务提供方。如果在访问服务提供方时出现大量错误(阀值:5秒中出错20次,5秒中有一半的请求出错)此时断器就会打开,断路器打开之后就不能访问服务提供方。但是过5秒种之后这个断路器又会自动转换为半开状态,此时允许少量的请求过来,如果请求成功次数达预定的阀值。此时断路器又自动被关闭,请求又恢复正常

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值