SpringCloud 之 Hystrix使用流程

Hystrix概念

Hystrix 是一个供分布式系统使用,提供延迟和容错功能,保证复杂的分布系统在面临不可避免的失败时,仍能有其弹性。
比如系统中有很多服务,当某些服务不稳定的时候,使用这些服务的用户线程将会阻塞,如果没有隔离机制,系统随时就有可能会挂掉,从而带来很大的风险。
SpringCloud使用Hystrix组件提供断路器、资源隔离与自我修复功能。

使用流程

1. pom引入依赖

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

2. 调用方的application配置中开启熔断机制

#开启熔断机制
feign.hystrix.enabled=true
# 设置hystrix超时时间,默认1000ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000

3. client包里面创建熔断器的实现类

@Component
public class VodServiceClientImpl implements VodServiceClient {
    //出错了才会执行以下方法
    @Override
    public CommonResponseVo deleteVideo(String id) {
        return CommonResponseVo.onfailed("熔断器:删除视频出错了");
    }
}

4. 修改client包中接口的注解

@FeignClient(name = "service-vod",fallback = VodServiceClientImpl.class)
                                  //fallback 指定出错了之后回调的类

5. 测试熔断器

@RestController
@RequestMapping("/eduservice/eduVideo")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;
    @Autowired
    private VodServiceClient vodServiceClient;

    @DeleteMapping("/delete/{id}")
    public CommonResponseVo deleteVideo(@PathVariable String id) {
        //从阿里云删除视频
        String videoSourceId = videoService.getById(id).getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
        	/*
        	这里远程调用服务,为了测试熔断,将远程服务关掉,最终会执行VodServiceClientImpl中定义的错误回调方法
        	*/
            CommonResponseVo result = vodServiceClient.deleteVideo(videoSourceId);
            if(result.getCode() == 20001){
                throw new GuliException(20001,"删除视频失败");
            }
        }
        //删除mysql中的记录
        boolean b = videoService.removeById(id);
        return CommonResponseVo.onSuccess(b);
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值