SpringCloud之熔断器使用(Hystrix)

前言

熔断器(Hystrix)的作用就是为了保护被调用方、自身不会因为某一个服务请求超时或者某个服务不可用而导致整个请求链路挂掉,防止雪崩效应导致这个系统不可用。同时在熔断器的实现中可以很好的实现服务监控,利于运营维护人员进行及时问题排除。这一篇文章我们主要讲如何去使用熔断器,更多的详细文档可以进入github熔断器项目中查看,hystrix开源项目

使用记录

1.pom添加hystrix依赖

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

[email protected](fallbackMethod = "saveOrderFail")进行注解实现熔断

package com.ckmike.order_service.controller;

import com.ckmike.order_service.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OrderController 简要描述
 * <p> TODO:描述该类职责 </p>
 *
 * @author ckmike
 * @version 1.0
 * @date 18-11-7 下午11:49
 * @copyright ckmike
 **/
@RestController
@RequestMapping("/api/v1/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("saveforribbon")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object saveforRibbon(@RequestParam("user_id") int userId,@RequestParam("product_id") int productId){
        return  this.orderService.saveForRibbon(userId,productId);
    }

    @RequestMapping("saveforfeign")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object saveforFeign(@RequestParam("user_id") int userId,@RequestParam("product_id") int productId){
        return  this.orderService.saveForFeign(userId,productId);
    }

    // 方法参数签名必须与api一致
    private Object saveOrderFail(int userId, int productId){
        // 监控报警机制
        new Thread(()->{
            String saveOrderKey = "save-order";
            String sendValue = redisTemplate.opsForValue().get(saveOrderKey);

            if(StringUtils.isBlank(sendValue)){
                // 发送警告消息
                System.out.println("紧急消息,用户下单失败,请尽快处理查找原因.");
                redisTemplate.opsForValue().set(saveOrderKey, "save-order-fali", 30, TimeUnit.SECONDS);
            } else {
                System.out.println("已经发送消息,30秒内不可重复发送。");
            }
        }).start();

        Map<String,Object> fallbackResponse = new HashMap();
        fallbackResponse.put("code", -100);
        fallbackResponse.put("msg","请求人数过多,请稍后再试。");
        return fallbackResponse;
    }
}

说明:在订单服务调用产品服务出现熔断的处理过程,上面还使用redis作为检查一段时间内是否以及发送监控通知信息,熔断后直接返回兜底数据,防止整个链路出现死等。hystrix主要就是通过@HystrixCommand进行使用。

feign结合Hystrix使用

我们可以通过查看feign的pom可以发现feign已经集合了Hystrix,默认情况下是关闭的,那么如何实现feign上使用Hystrix呢?

1.pom引入Hystrix依赖,这一步是必须要的
2.查看@FeignClient源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.cloud.openfeign;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
    @AliasFor("name")
    String value() default "";

    /** @deprecated */
    @Deprecated
    String serviceId() default "";

    @AliasFor("value")
    String name() default "";

    String qualifier() default "";

    String url() default "";

    boolean decode404() default false;

    Class<?>[] configuration() default {};

    Class<?> fallback() default void.class;

    Class<?> fallbackFactory() default void.class;

    String path() default "";

    boolean primary() default true;
}

我们可以看到上面有一个fallback和fallbackFactory属性,其实我们就可以实现一个fallback类去处理FeignClient中fallback的情况。
3.实现ProductService的客户端调用时fallback处理

package com.ckmike.order_service.fallback;

import com.ckmike.order_service.service.ProductClient;
import org.springframework.stereotype.Component;

/**
 * ProductServiceFallBack 简要描述
 * <p> TODO:描述该类职责 </p>
 *
 * @author ckmike
 * @version 1.0
 * @date 18-11-23 下午2:04
 * @copyright ckmike
 **/
@Component
public class ProductServiceFallBack implements ProductClient {

    @Override
    public String findById(int id) {
        System.out.println("产品服务调用失败!!!!!");
        System.out.println("调用监控消息组件进行消息发送。");
        return null;
    }
}

package com.ckmike.order_service.service;

import com.ckmike.order_service.fallback.ProductServiceFallBack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @ClassName ProductClient产品服务客户端
 * @Description TODO:描述该接口职责
 * @Author ckmike
 * @Date 18-11-22 下午4:10
 * @Version 1.0
 * @Copyright ckmike
 **/
@FeignClient(name="product-service", fallback = ProductServiceFallBack.class)
public interface ProductClient {

    @GetMapping("/api/v1/product/find")
    String findById(@RequestParam(value = "id") int id);
}

4.配置开启feign中hystrix(默认情况下是关闭的)

#feign组件的配置
feign:
  #默认是关闭的
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeOut: 2000
        readTimeOut: 2000

总结

1.hystrix能够保护调用方和被调用方,防止请求链路因为某一个服务失败而产生雪崩效应。
2.hystrix的隔离熔断策略有线程、信号量两种方式,具体可查看源码
3.熔断器中实现监控是非常有用且非常有必要的,对于运营与维护具有重大意义。

关于SpringCloud相关博客的源代码,在我码云上已经上传,有需要的可以查看SpringCloud项目源代码

原文地址:http://blog.51cto.com/4837471/2321447

时间: 2024-08-30 06:06:58

SpringCloud之熔断器使用(Hystrix)的相关文章

springcloud入门之断路器Hystrix(四)

什么是断路器 断路器模式源于Martin Fowler的Circuit Breaker一文."断路器"本身是一种开关装置,用于在电路上保护线路过载,当线路中有电器发生短路时,"断路器"能够及时的切断故障电路,防止发生过载.发热.甚至起火等严重后果. 在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障(类似用电器发生短路)之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个错误响应,而不是长时间的等待.这样就不会使得线程因调用故障服务被长时间

Spring-cloud(六) Hystrix入门

前提 一个可用的Eureka注册中心(文中以之前博客中双节点注册中心,不重要) 一个连接到这个注册中心的服务提供者 快速入门 项目搭建 搭建一个新maven项目,artifactid为Ribbon-consum-hystrix,依赖是在ribbon-customer项目上加入hystrix依赖,这里直接给出,pom.xml配置如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&quo

SpringCloud之断路器监控(Hystrix Dashboard)(九)

断路器断路器模式源于Martin Fowler的Circuit Breaker一文."断路器"本身是一种开关装置,用于在电路上保护线路过载,当线路中有电器发生短路时,"断路器"能够及时的切断故障电路,防止发生过载.发热.甚至起火等严重后果. 在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障(类似用电器发生短路)之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个错误响应,而不是长时间的等待.这样就不会使得线程因调用故障服务被长时间占用不释

SpringCloud(六)Hystrix配置

hystrix.command.default和hystrix.threadpool.default中的default为默认CommandKey Execution相关的属性的配置: hystrix.command.default.execution.isolation.strategy隔离策略,默认是Thread, 可选Thread|Semaphore hystrix.command.default.execution.isolation.thread.timeoutInMillisecond

SpringCloud学习笔记(3)——Hystrix

参考Spring Cloud官方文档第13.14.15章 13. Circuit Breaker: Hystrix Clients Netflix提供了一个叫Hystrix的类库,它实现了断路器模式.在微服务架构中,通常一个微服务会调用多个其他的微服务.一个相对低层级的服务失败可能造成上层应用的级联失败,服务访问量越大失败率越高.当断路打开的时候,这个调用就被终止了.打开的断路可以阻止级联失败. 13.1 How to Include Hystrix 15.1 How to Include Hy

SpringCloud系列七:Hystrix 熔断机制(Hystrix基本配置、服务降级、HystrixDashboard服务监控、Turbine聚合监控)

1.概念:Hystrix 熔断机制 2.具体内容 所谓的熔断机制和日常生活中见到电路保险丝是非常相似的,当出现了问题之后,保险丝会自动烧断,以保护我们的电器, 那么如果换到了程序之中呢? 当现在服务的提供方出现了问题之后整个的程序将出现错误的信息显示,而这个时候如果不想出现这样的错误信息,而希望替换为一个错误时的内容. 一个服务挂了后续的服务跟着不能用了,这就是雪崩效应 对于熔断技术的实现需要考虑以下几种情况: · 出现错误之后可以 fallback 错误的处理信息: · 如果要结合 Feign

SpringCloud学习系列之三----- 断路器Hystrix和断路器监控Dashboar

前言 本篇主要介绍的是SpringCloud中的断路器(Hystrix)和断路器指标看板(Dashboard)的相关使用知识. SpringCloud Hystrix Hystrix 介绍 Netflix创建了一个名为Hystrix的库,它实现了断路器模式.主要的目的是为了解决服务雪崩效应的一个组件,是保护服务高可用的最后一道防线. 开发准备 开发环境 JDK:1.8 SpringBoot:2.1.1.RELEASE SpringCloud:Finchley 注:不一定非要用上述的版本,可以根据

SpringCloud(一):SpringCould 框架预览

前言 SpringCloud是基于SpringBoot的一整套实现微服务的框架.他提供了微服务开发所需的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布式会话和集群状态管理等组件.最重要的是跟spring boot框架一起使用的话,会让你开发微服务架构的云服务非常好的方便. SpringBoot旨在简化创建产品级的 Spring 应用和服务,简化了配置文件,使用嵌入式web服务器,含有诸多开箱即用微服务功能. 基于SpringCloud的微服务框架: ? Sprin

SpringCloud和Springboot

SpringBoot+SpringCloud+SpringMVC+SpringData 我们把这种架构也称之为spring全家桶 什么是SpringCloudSpring Cloud是一系列框架的有序集合.它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册.配置中心.消息总线.负载均衡.熔断器.数据监控等,都可以用Spring Boot的开发风格做到一键启动和部署.Spring并没有重复制造轮子,它只是将目前各家公司开发的比较成熟.经得起实际考验的服务框