springcloud 之 熔断和降级

springcloud 熔断和降级,当服务集群中有个别服务提供者出现故障或者无法提供服务的时候,如果不断的去请求该服务,就会消耗更多的网络请求资源,甚至引起整个服务集群的瘫痪。这就好像电路一样,当电路短路的时候,如果没有保险丝后果是可想而知的。同样的道理,springcloud 引入了hystrix 组件作为服务集群间的保险丝。下面我们就来看springcloud是如何利用hystrix 组件来实现熔断与降级的。

1.熔断

 pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

application.yml 配置

eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8081/eureka/
server:
  port: 8085
spring:
  application:
    name: order_service

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 2000
        readTimeout: 2000

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000
      circuitBreaker:
        requestVolumeThreshold: 1
        errorThresholdPercentage: 1
        sleepWindowInMilliseconds: 15000
      metrics:
        rollingStats:
          timeInMilliseconds:100000

为了能够做熔断测试,配置在100秒之内出现熔断触发的最小个数1,错误率达到1%,每15秒检查一次。

OrderServiceApplication 代码

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class OrderServiceApplication {

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

OrderController 代码

@RestController
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private ProductClient productClient;


    @RequestMapping("getOrderDetailById.do")
    @HystrixCommand(fallbackMethod = "getOrderDetailFallback")
    public Object  getOrderDetailById(@RequestParam("productId") int productId){
        Order  order=new Order();
        order.setOrderId(1);
        String json=productClient.getProductDetailById(productId);
        JSONObject jsonObject=JSONObject.parseObject(json);
        System.out.println(jsonObject.get("productName"));
        return json;
    }


    public String getOrderDetailFallback(int productId, Throwable t) {
        return "getOrderDetailFallback:" + productId + "," + t.getMessage();
    }

getOrderDetailFallback 方法即为 降级方法。降级处理可以写在这里面。整体效果如下图:

正常图

发生故障后熔断降级

猜你喜欢

转载自blog.csdn.net/qq_40263927/article/details/110107816