微服务——服务降级(熔断器)

问题

当我们微服务关闭或者找不到的时候,前端的请求会出现这样的问题。
前端问题展示:
在这里插入图片描述
后端报错展示:
在这里插入图片描述
开发中出现这样的问题是不允许的,不仅前端阅读性差,后端也直接报错。

解决此问题的组件介绍

SpringCloud服务组件:
服务降级组件(熔断器):Hystrix、Resilience4J、sentienl
1.Hystrix:已经停止更新不推荐使用
2.Resilience4J:国外使用较多
3.sentienl:阿里巴巴开发的(推荐)

怎么使用

第一步:先引入pom依赖

<!--服务降级,熔断器-->
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-alibaba-sentinel -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>

第二步:添加springboot配置,打开容错机制

第一种:

feign:
  sentinel:
    enabled: true

第二种:(这种是hystrix的配置,openFeign中父pom包含htstrix的依赖)
hystrix的配置

feign:
  hystrix:
    enabled: true

第三步:在FeignClient注解上添加配置,并且创建继承该类的实现类

@FeignClient(value = "house-service", fallback = SupportSubwayFeignImpl.class)
public interface SupportSubwayFeign {

    @GetMapping("address/support/subway/line/{cityName}")
    @ResponseBody
    public ViewResult getSupportSubway(@PathVariable("cityName") String cityName);

}
@Component
public class SupportSubwayFeignImpl implements SupportSubwayFeign {
    @Override
    public ViewResult getSupportSubway(String cityName) {
        ViewResult result = new ViewResult();
        result.setMessage("找不到服务");
        result.setCode(ViewResult.Status.SERVERERROR.getCode());
        return result;
    }
}

第四步:打开postman测试

在这里插入图片描述
正确返回结果,测试成功。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值