springcloud 降级

本文介绍了如何在微服务架构中利用Hystrix进行服务间的熔断和降级。主要涉及Eureka作为注册中心,以及product-server和order-server两个微服务。配置了Hystrix依赖,并在SpringBoot启动类中启用Feign和CircuitBreaker。通过调整Feign客户端的超时时间和启用Hystrix支持,确保服务的稳定性和容错性。

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

Hystrix:

      使用到的组件包括:Eureka、Feign包括以下三个项目:

    (1)Eureka-server:   7001    注册中心

    (2)product-server :8001   X微服务

    (3)order-server :   9001   Y微服务

    1、pom.xml

        <!--hystrix依赖,主要是用  @HystrixCommand -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

   2、application.yml

复制代码

server:
  port: 9001

#指定注册中心地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:7001/eureka/

#服务的名称
spring:
  application:
    name: order-service
    
#开启feign支持hystrix  (注意,一定要开启,旧版本默认支持,新版本默认关闭)
# #修改调用超时时间(默认是1秒就算超时)
feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 2000
        readTimeout: 2000

复制代码

 3、SpringBoot启动类

@SpringBootApplication
@EnableFeignClients
//添加熔断降级注解
@EnableCircuitBreaker
public class AAApplication {

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

}

https://www.cnblogs.com/qdhxhz/p/9581440.html

### Spring Cloud 中的服务降级 #### 超时降级 当服务调用超过预设的时间阈值未返回结果时,会触发超时降级机制。这种情况下,系统不会等待该请求完成而是立即执行预先定义好的回退逻辑[^2]。 ```java @HystrixCommand(fallbackMethod = "timeoutFallback", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) public String callService() { // Service invocation logic here... } private String timeoutFallback() { return "The service took too long to respond."; } ``` #### 限流降级 为了防止过多的并发访问压垮下游服务,在达到设定的最大请求数量之后新的请求会被拒绝并进入降级处理流程。这有助于保护整个系统的稳定性。 #### 异常降级 如果目标服务抛出了未经捕获的异常,则自动激活此类型的降级策略。此时可以自定义错误响应给客户端或者记录日志以便后续排查问题所在。 ```java @HystrixCommand(fallbackMethod = "exceptionFallback") public String invokeRemoteService() throws Exception { try { // Remote service calling code goes here. } catch (Exception e) { throw new RuntimeException(e); } } private String exceptionFallback(Throwable t) { logger.error("An error occurred while invoking remote service.", t); return "There was an issue processing your request."; } ``` #### 熔断降级 一旦检测到某个特定时间段内失败率超过了指定比例,熔断器就会打开阻止进一步尝试直到恢复期结束。这种方式能够有效避免故障扩散影响其他正常运行的部分。 对于最佳实践方面: - **全局统一管理**:尽可能把所有可能发生的场景都考虑到,并且通过集中式的配置文件来管理和调整各个参数设置。 - **合理设计兜底方案**:针对不同业务需求制定相应的默认行为或提示信息,确保即使出现问题也不会让用户感到困惑。 - **监控与报警机制完善**:及时发现潜在风险点以及已经发生过的事件,从而采取措施加以改进优化[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值