当前位置: 代码网 > it编程>编程语言>Java > Spring Cloud Hystrix服务容错问题及解决

Spring Cloud Hystrix服务容错问题及解决

2026年10月10日 • Java •我要评论
一、前言在微服务的架构中,服务间通常会形成相互依赖的关系,比如现在有三个微服务节点:a,b和c,b为a的消费者,c为b的消费者。假如由于网络波动或者a服务自身故障,导致b调用a服务的线程被挂起进入长时

一、前言

在微服务的架构中,服务间通常会形成相互依赖的关系,比如现在有三个微服务节点:a,b和c,b为a的消费者,c为b的消费者。假如由于网络波动或者a服务自身故障,导致b调用a服务的线程被挂起进入长时间的等待。在高并发的情况下可能导致b的资源被耗竭随之崩溃,从而导致c服务也不可用。这种连环式的雪崩效应在微服务中较为常见,为了解决这个问题,服务熔断技术应运而出。熔断一词来自电路学,指的是电路在出现短路状况时,“断路器”能够及时地切断故障电路,避免电路过载发热引发火灾。

类似的,微服务架构中的断路器能够及时地发现故障服务,并向服务调用方返回错误响应,而不是长时间的等待。spring cloud hystrix在hystrix(又是一款由netflix开发的开源软件,github地址https://github.com/netflix/hystrix的基础上进行了封装,提供了服务熔断,服务降级,线程隔离等功能,通过这些功能可以提供服务的容错率。

二、介绍

2.1 请求熔断

断路器是一种开关设置,当某个服务单元发生故障之后,通过断路器的故障监控,向调用方返回一个符合预期的服务降级处理(fallback),而不是长时间的等待或者抛出调用方无法处理的异常,这样保证了服务调用方的线程不会长时间被占用,从而避免了故障在分布式系统的蔓延乃至崩溃。

2.2 服务降级

fallback 相当于是降级操作。对于查询操作, 我们可以实现一个 fallback 方法, 当请求后端服务出现异常的时候, 可以使用 fallback 方法返回的值。

fallback 方法的返回值一般是设置的默认值或者来自缓存,告知后面的请求服务不可用了,不要再请求了。

2.3 请求熔断和服务降级区别

2.3.1 相同点

  • 目标一致:为了防止系统崩溃而实施的一种防御手段
  • 表现形式一致:当请求目标在一定时间内无响应时,返回或执行默认响应内容

2.3.2 不同

  • 触发条件不同:下游服务出现故障触发请求熔断。系统负荷超过阈值触发服务降级。
  • 管理目标层次不同:请求熔断针对所有微服务。服务降级针对整个系统中的外围服务。

三、请求熔断实战

本次测试案例基于之前发表的文章中介绍的案例进行演示。

现在的项目列表如下:

项目服务实例实例id端口描述
common-api无无无公用的 api,如:实体类
eureka-servereureka-servereureka-server19001注册中心(eureka 服务端)
eureka-servereureka-servereureka-server29002注册中心(eureka 服务端)
goods-servergoods-servergoods-server18801商品服务(eureka 客户端)
goods-servergoods-servergoods-server28802商品服务(eureka 客户端)
goods-servergoods-servergoods-server38803商品服务(eureka 客户端)
order-serverorder-weborder-web8900订单服务(eureka 客户端)

3.1 common-api

3.1.1 增加goods实体

goods.java

@data
@noargsconstructor
@allargsconstructor
@tostring
public class goods implements serializable {

    private static final long serialversionuid = -8143412915723961377l;

    private string goodsid;

    private string name;

    private string descr;

    // 测试端口
    private int port;

    private string instanceid;

}

3.1.2 增加order实体

order.java

@data
@noargsconstructor
@allargsconstructor
@tostring
public class order implements serializable {

    private static final long serialversionuid = -8143412915723961379l;

    private string orderid;

    private string goodsid;

    private int num;

}

3.1.3 增加result实体

result.java

@getter
@tostring
public class result implements serializable {

    private static final long serialversionuid = -8143412915723961323l;

    private int code;

    private string msg;

    private object data;

    private result() {}

    private result(int code, string msg) {
        this.code = code;
        this.msg = msg;
    }

    private result(int code, string msg, object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static result success() {
        return success(null);
    }

    public static result success(object data) {
        return new result(200, "success", data);
    }

    public static result fail() {
        return fail(500, "fail");
    }

    public static result fail(int code, string message) {
        return new result(code, message);
    }

}

3.2 goods-server

3.2.1 服务配置

新建一个eureka客户端,创建三个application-xxx.yml

application-goodsserver01.yml

server:
  port: 8801
spring:
  application:
    name: goods-server
eureka:
  instance:
    instance-id: goods-server1
    prefer-ip-address: off
  client:
    register-with-eureka: true     # 是否向注册中心注册自己
    fetch-registry: true           # 是否检索服务
    service-url:
      defaultzone: http://eureka01:9001/eureka/,http://eureka02:9002/eureka/

application-goodsserver02.yml

server:
  port: 8802
spring:
  application:
    name: goods-server
eureka:
  instance:
    instance-id: goods-server2
    prefer-ip-address: off
  client:
    register-with-eureka: true     # 是否向注册中心注册自己
    fetch-registry: true           # 是否检索服务
    service-url:
      defaultzone: http://eureka01:9001/eureka/,http://eureka02:9002/eureka/

application-goodsserver03.yml

server:
  port: 8803
spring:
  application:
    name: goods-server
eureka:
  instance:
    instance-id: goods-server3
    prefer-ip-address: off
  client:
    register-with-eureka: true     # 是否向注册中心注册自己
    fetch-registry: true           # 是否检索服务
    service-url:
      defaultzone: http://eureka01:9001/eureka/,http://eureka02:9002/eureka/

分别对应的service和启动参数如下:

service启动参数
goodsserverapplication-goodsserver01-8801spring.profiles.active=goodsserver01
goodsserverapplication-goodsserver02-8802spring.profiles.active=goodsserver02
goodsserverapplication-goodsserver03-8803spring.profiles.active=goodsserver03

3.2.2 创建service

goodsservice.java

public interface goodsservice {
    goods findgoodsbyid(string goodsid) ;
}

具体实现goodsserviceimpl.java

@service
public class goodsserviceimpl implements goodsservice {

    @value("${eureka.instance.instance-id}")
    private string instanceid;

    @value("${server.port}")
    private int port;

    // 模拟数据库
    private static map<string, goods> data;

    static {
        data = new hashmap<>();
        data.put("1", new goods("1", "手机", "国产手机", 0,""));
        data.put("2", new goods("2", "电脑", "台式电脑", 0,""));
    }

    @override
    public goods findgoodsbyid(string goodsid) {
        goods goods = data.get(goodsid);
        if (goods == null) {
            throw new runtimeexception("商品不存在");
        }
        goods.setport(port);
        goods.setinstanceid(instanceid);
        return goods;
    }
}

3.2.3 创建controller

goodscontroller.java

@restcontroller
@requestmapping("/goods")
public class goodscontroller {

    @autowired
    private goodsservice goodsservice;

    @requestmapping("/goodsinfo/{goodsid}")
    public result goodsinfo(@pathvariable string goodsid) {
        goods goods = this.goodsservice.findgoodsbyid(goodsid);
        return result.success(goods);
    }

}

3.2 order-server

新建一个eureka客户端

3.2.1 引入依赖

        <dependency>
            <groupid>org.springframework.cloud</groupid>
            <artifactid>spring-cloud-starter-netflix-hystrix</artifactid>
        </dependency>

3.2.2 创建server

orderservice.java

public interface orderservice {
    result placeorder(order order) throws exception;
}

3.3.3 创建controller

@restcontroller
@requestmapping("/order")
public class ordercontroller {

    @autowired
    private orderservice orderservice;

    @requestmapping("/place")
    public result placeorder(order order) throws exception {
        this.orderservice.placeorder(order);
        return result.success();
    }

}

3.4 设置熔断策略

编写orderservice具体实现类

orderserviceimpl.java

@service
public class orderserviceimpl implements orderservice {

    @autowired
    private resttemplate resttemplate;

    @hystrixcommand(fallbackmethod = "defaultbyplaceorder")
    @override
    public result placeorder(order order) throws exception {

        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);

        if (result != null && result.getcode() == 200) {
            system.out.println("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

    public result defaultbyplaceorder(order order) {
        system.out.println("商品服务系统异常");
        return result.fail(500, "商品服务系统出现异常,请联系管理员");
    }

}

当调用商品服务超时或出现异常时,hystrix 会调用 @hystrixcommand 中指定的 fallbackmethod 方法获取返回值或执行异常处理。

注意:fallbackmethod 方法要求与正常方法有相同的入参和回参。

3.5 启动熔断功能

在启动类上添加@enablehystrix或者@enablecircuitbreaker注解,这两个注解是等价的,查看@enablehystrix注解源码就可以证实这一点:

@target({elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@inherited
@enablecircuitbreaker
public @interface enablehystrix {
}

在引入@enablehystrix或者@enablecircuitbreaker注解后,我们的入口类代码如下:

@enablehystrix
@enableeurekaclient
@springbootapplication
public class orderserverapplication {

    public static void main(string[] args) {
        springapplication.run(orderserverapplication.class, args);
    }

}

入口类上总共包含了三个注解@enablecircuitbreaker、@enablediscoveryclient和@springbootapplication,这三个注解的组合可以使用@springcloudapplication来代替,@springcloudapplication源码如下:

@target({elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@inherited
@springbootapplication
@enablediscoveryclient
@enablecircuitbreaker
public @interface springcloudapplication {
}

3.6 熔断测试

我们首先演示没有开启熔断的功能,即先把上边的 @enablecircuitbreaker 注解进行注释。

启动好所有项目,使用 idea 请求 order-server 进行下单操作,运行结果如下:

当我们请求发送的 goodsid 的商品不存在,服务提供方抛会异常,调用方无法处理,因此只能展示图中的异常信息。

下面,我们再将 @enablecircuitbreaker 注解的注释放开,运行结果如下:

从图中可知,虽然请求了一个 goodsid 不存在的商品,但是调用方(order-server)开启了熔断机制,执行默认方法,从而使接口能正常通信而不是抛出调用方不可处理的异常导致整个系统不能正常运行。

看到这里,或许会有读者产生一个疑问,如果类中定义 n 个方法,是不是意味着同时也要定义 n 个异常处理的方法呢,答案是否定的。

hystrix 还提供了 @defaultproperties 统一处理请求熔断,在该注解上设置 defaultfallback 属性值,即熔断开启后要执行的方法。

@defaultproperties(defaultfallback = "defaultbyhystrix")
@service
public class orderserviceimpl implements orderservice {

    @autowired
    private resttemplate resttemplate;

    @hystrixcommand
    @override
    public result placeorder(order order) throws exception {
        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);
        if (result != null && result.getcode() == 200) {
            system.out.println("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;

    }

    public result defaultbyhystrix() {
        system.out.println("商品服务系统异常");
        return result.fail(500, "商品服务系统出现异常,请联系管理员");
    }

}

注意:defaultfallback 定义的方法必须是无参的,但是返回值必须与报错的方法返回一致。

四、服务降级

4.1 定义 fallback

在 common-api 项目中:

@component
public class goodsserviceclientfallbackfactory implements fallbackfactory<goodsserviceclient> {

    @override
    public goodsserviceclient create(throwable throwable) {
        return new goodsserviceclient() {
            @override
            public result goodsinfo(string goodsid) {
                return result.fail(500, "商品服务系统出现异常,请联系管理员");
            }
        };
    }

}

使用单独的类处理异常逻辑,当与服务端无法正常通信时调用此类中的方法返回结果。

4.2 修改 feign 客户端

@feignclient(value="goods-server", fallbackfactory = goodsserviceclientfallbackfactory.class)
public interface goodsserviceclient {
    @requestmapping("/goods/goodsinfo/{goodsid}")
    public result goodsinfo(@pathvariable("goodsid") string goodsid);
}

4.3 开启服务降级功能

在 order-server 项目中:

server:
  port: 8900
spring:
  application:
    name: order-web
eureka:
  instance:
    instance-id: order-web
    prefer-ip-address: off
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultzone: http://eureka01:9001/eureka/,http://eureka02:9002/eureka/
feign:
  hystrix:
    enabled: true

4.4 去掉 @hystrixcommand 配置

@service
public class orderserviceimpl implements orderservice {

    @autowired
    private goodsserviceclient goodsserviceclient;

    @override
    public result placeorderhystrix(order order) throws exception {
        result result = this.goodsserviceclient.goodsinfo(order.getgoodsid());
        if (result != null && result.getcode() == 200) {
            system.out.println("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

}

4.5 测试服务降级

在启动类上加 fallbackfactory 类的包扫描目录:

@enablecircuitbreaker
@enablefeignclients(basepackages = {"com.wno704.cloud"})
@enableeurekaclient
@springbootapplication
public class orderserverapplication {
    public static void main(string[] args) {
        springapplication.run(orderserverapplication.class, args);
    }
}

打开 idea 请求下单接口,结果如下图:

我们手动关闭 2 个商品服务,保留一个商品服务并多次请求商品服务接口,从而出模拟商品服务超过预定荷载情景,最终看到图中服务降级功能。

当有请求再次访问商品服务时默认返回 goodsserviceclientfallbackfactory 中定义的内容。

五、@hystrixcommand详解

@hystrixcommand注解还包含许多别的属性功能,下面介绍一些常用的属性配置。

5.1 服务降级

3.4 设置熔断策略中的placeorder中我们用@hystrixcommand注解指定了服务降级方法defaultbyplaceorder。如果placeorder方法也抛出异常,那么我们可以再次使用@hystrixcommand注解指定placeorder方法降级的方法,比如定义一个defaultbyplaceorder2方法:

    @hystrixcommand(fallbackmethod = "defaultbyplaceorder2"})
    @override
    public result placeorder(order order) throws exception {
        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);
        if (result != null && result.getcode() == 200) {
            log.info("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

    public result defaultbyplaceorder2(order order) {
        system.out.println("商品服务系统异常");
        return result.fail(500, "商品服务系统出现异常,请联系管理员");
    }

重启order-server,访问http://localhost:8900/order/place,我们可以获取一个不存在的goodsid

5.2 异常处理

在使用@hystrixcommand注解标注的方法中,除了hystrixbadrequestexception异常外,别的异常都会触发服务降级。

假如我们想指定某个异常不触发服务降级,可以使用@hystrixcommand注解的ignoreexceptions属性进行忽略。

此外,对于方法抛出的异常信息,我们可以在服务降级的方法中使用throwable对象获取,如:

    @hystrixcommand(fallbackmethod = "defaultbyplaceorder2"})
    @override
    public result placeorder(order order) throws exception {
        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);
        if (result != null && result.getcode() == 200) {
            log.info("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

    public result defaultbyplaceorder2(order order, throwable e) {
        system.out.println("商品服务系统异常");
        return result.fail(500, "商品服务系统出现异常,请联系管理员");
    }

5.3 命名与分组

通过指定@hystrixcommand注解的commandkey、groupkey以及threadpoolkey属性可以设置命令名称、分组以及线程池划分,如:

@hystrixcommand(fallbackmethod = "defaultbyplaceorder2",ignoreexceptions = {nullpointerexception.class},
            commandkey = "placeorderbygoodid", groupkey = "ordergroup",threadpoolkey = "getgoodthread")

    @override
    public result placeorder(order order) throws exception {
        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);
        if (result != null && result.getcode() == 200) {
            log.info("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

上面的配置指定了命令的名称为placeorderbygoodid,组名为ordergroup,线程池名称为getgoodthread。

通过设置命令组,hystrix会根据组来组织和统计命令的告警、仪表盘等信息。默认情况下,hystrix命令通过组名来划分线程池,即组名相同的命令放到同一个线程池里,如果通过threadpoolkey设置了线程池名称,则按照线程池名称划分。

当placeorder方法被调用时,日志打印如下:

可看到线程名称为getgoodthread-2。

5.4 hystrix缓存

5.4.1 开启缓存

要在hystrix中开启缓存很简单,只需使用@cacheresult注解即可,新增orderserviceimpl的placeordercache方法:

我们在controller中调用三次testcache方法,参数都为goodsid=1&num=1:

    public string getcachekey(string goodsid) {
        return goodsid;
    }

    @cacheresult(cachekeymethod = "getcachekey")
    @override
    public result placeordercache(@cachekey("goodsid") order order) throws exception {
        result result = this.resttemplate.getforobject("http://goods-server/goods/goodsinfo/" + order.getgoodsid(), result.class);
        if (result != null && result.getcode() == 200) {
            log.info("=====下订单====");
            system.out.println(result.getdata());
        } else {
            system.out.println(result.getmsg());
        }
        return result;
    }

我们也可以明确的指定缓存的key值是什么。指定key的值有两种方式:

1.通过@cachekey注解指定,如:

@cacheresult(cachekeymethod = “getcachekey”)
public result placeordercache(@cachekey(“goodsid”) string goodsid)

也可以指定参数对象内部属性为key值:

@cacheresult(cachekeymethod = “getcachekey”)
public result placeordercache(@cachekey(“goodsid”) order order)

2.通过方法来指定,方法的返回值必须是string类型:

如上面示例所示。

值得注意的是,方法2的优先级比方法1高。

5.4.2 缓存清除

在涉及到更新user信息的方法上,我们要及时的清除相应的缓存,否则将会导致缓存数据和实际数据不一致的问题。我们在userservice的updateuser方法上做缓存清除操作:

@cacheremove(cachekeymethod = “getcachekey”)
public result deleteordercache(@cachekey(“goodsid”) order order)

@cacheremove的commandkey属性和getuser里定义的一致。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

赞 (0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com