所谓的熔断机制和日常生活中见到电路保险丝是非常相似的,当出现了问题之后,保险丝会自动烧断,以保护我们的电器, 那么如果换到了程序之中呢?

当现在服务的提供方出现了问题之后整个的程序将出现错误的信息显示,而这个时候如果不想出现这样的错误信息,而希望替换为一个错误时的内容。

一个服务挂了后续的服务跟着不能用了,这就是雪崩效应

对于熔断技术的实现需要考虑以下几种情况:

· 出现错误之后可以 fallback 错误的处理信息;

· 如果要结合 Feign 一起使用的时候还需要在 Feign(客户端)进行熔断的配置。

一、基于ribbon的Hystrix 基本配置

1、复制项目重命名为springcloud-moveServer-hystrix修改调用方 pom.xml 配置文件,追加 Hystrix 配置类:

 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>

2.修改程序 controller

package com.pupeiyuan.controller;

import java.util.ArrayList;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.pupeiyuan.bean.NhReportStatusHistory; @RestController
@RefreshScope
public class ConfigClientController { //spring 提供用于访问rest接口的模板对象
@Autowired
@Qualifier(value = "remoteRestTemplate")
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "findByIdFallback")
@GetMapping("/balance/{id}")
public List<NhReportStatusHistory> getBalance(@PathVariable Long id) {
return this.restTemplate.getForObject("http://MULTIPLE/getDate/"+id, List.class); }
public List<NhReportStatusHistory> findByIdFallback(Long id) {
NhReportStatusHistory nhreportstatushistory = new NhReportStatusHistory();
nhreportstatushistory.setId("000000000000");
List<NhReportStatusHistory> list = new ArrayList<>();
list.add(nhreportstatushistory);
return list;
}
}

这里需要注意的是,fallback方法的参数和类型要和原方法保持一致,否则会出现异常

3、在主类之中启动熔断处理

package com.pupeiyuan.config;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate; import feign.Logger; @Configuration
//扫描bean
@ComponentScan(basePackages = "com.pupeiyuan.*")
//不用自动配置数据源
@EnableDiscoveryClient
@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
@EnableFeignClients(basePackages="com.pupeiyuan.feignClient")
@EnableCircuitBreaker
public class MainApplication extends SpringBootServletInitializer { @Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
//相当于xml中的bean标签 用于调用当前方法获取到指定的对象
@Bean(name="remoteRestTemplate")
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MainApplication.class);
}
}

到此,一个简单基于ribbon的Hystix熔断机制就配置好了

二、基于Feign client的Hystrix 配置

1、复制项目重命名为springcloud-moveServer-hystrix修改调用方 pom.xml 配置文件,追加 Hystrix 配置类:

        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

2、增加配置启用

feign.hystrix.enabled=true

3、启动类增加注解

@EnableCircuitBreaker

4、增加FeignClient2业务接口,并配置fallback

package com.pupeiyuan.feignClient;

import java.util.List;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.config.FeignConfiguration;
import com.pupeiyuan.bean.NhReportStatusHistory; import feign.Param;
import feign.RequestLine; @FeignClient(name = "MULTIPLE",configuration = FeignConfiguration.class,fallback=HystrixClientFallback.class)
public interface FeignClient2 { @RequestMapping(value = "/getDate/{id}", method = RequestMethod.GET)
public List<NhReportStatusHistory> dataList(@PathVariable("id") Long id);
}

5.增加HystrixClientFallback类

package com.pupeiyuan.feignClient;

import java.util.ArrayList;
import java.util.List; import org.springframework.stereotype.Component; import com.pupeiyuan.bean.NhReportStatusHistory; @Component
public class HystrixClientFallback implements FeignClient2{ @Override
public List<NhReportStatusHistory> dataList(Long id) {
NhReportStatusHistory nhreportstatushistory = new NhReportStatusHistory();
nhreportstatushistory.setId("99999999999999");
List<NhReportStatusHistory> list = new ArrayList<>();
list.add(nhreportstatushistory);
return list;
} }

演示如下,停调multiple服务,请求结果

请求健康状态接口显示断路器已经在打开状态

三、如何禁用单个FegionClient的Hystrix的支持

在自定义Feign Client配置文件FeignConfiguration.java中新增配置即可

package com.pupeiyuan.feignClientConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; import feign.Contract;
import feign.Feign;
import feign.Logger;
@Configuration
public class FeignConfiguration { @Bean
public Contract feignContract() {
//这里可以配置默认配置
return new feign.Contract.Default();
} @Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
} @Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}

使用这个feign client配置文件的feign client都不会启用熔断器

四、Feign使用fallbackFactory属性打印fallback异常

1、基本配置略

2、配置UserFeignClient

@FeignClient(name = "microservice-provider-user",  fallbackFactory = HystrixClientFallbackFactory.class)
public interface UserFeignClient {
// @GetMapping("/sample/{id}")
@RequestMapping(method = RequestMethod.GET, value = "/sample/{id}")
public User findById(@PathVariable("id") Long id);
}

注意:配置了fallbackFactory ,如果同时设置fallback和fallbackfactory不可以有冲突,只能设置一个,fallbackFactory 是fallback的一个升级版

3、fallbackFactory 的类设置HystrixClientFallbackFactory

@Component
public class HystrixClientFallbackFactory implements FallbackFactory<UserFeignClient> {
private static final Logger logger = LoggerFactory.getLogger(HystrixClientFallbackFactory.class); @Override
public UserFeignClient create(Throwable arg0) {
HystrixClientFallbackFactory.logger.info("fallback reason was:{}", arg0.getMessage());
return new UserFeignClientWithFactory() {
@Override
public User findById(Long id) {
User user = new User();
user.setId(-1L);
return user;
}
};
}
}

4、UserFeignClientWithFactory设置

public interface UserFeignClientWithFactory extends UserFeignClient {

}

spring cloud Hystix熔断机制--基本熔断配置和Fegin client熔断配置的更多相关文章

  1. Spring Cloud Eureka 自我保护机制

    Eureka Server 在运行期间会去统计心跳失败比例在 15 分钟之内是否低于 85%,如果低于 85%,Eureka Server 会将这些实例保护起来,让这些实例不会过期,但是在保护期内如果 ...

  2. spring cloud 的自我保护机制

    spring cloud 的自我保护机制定义: 自我保护模式是:在出现网络异常波动的情况下,使用自我保护模式使eureka 集群更加健壮,稳定. 自我保护机制是:在15分钟内客户端没有雨注册中心发生心 ...

  3. Spring Cloud Eureka 自我保护机制实战分析

    前些天栈长在Java技术栈微信公众号分享过 Spring Cloud Eureka 的系列文章: Spring Cloud Eureka 自我保护机制 Spring Cloud Eureka 常用配置 ...

  4. Spring Cloud Gateway重试机制

    前言 重试,我相信大家并不陌生.在我们调用Http接口的时候,总会因为某种原因调用失败,这个时候我们可以通过重试的方式,来重新请求接口. 生活中这样的事例很多,比如打电话,对方正在通话中啊,信号不好啊 ...

  5. spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略

    spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略 某电子商务网站在一个黑色星期五 ...

  6. Spring Cloud 请求重试机制核心代码分析

    场景 发布微服务的操作一般都是打完新代码的包,kill掉在跑的应用,替换新的包,启动. spring cloud 中使用eureka为注册中心,它是允许服务列表数据的延迟性的,就是说即使应用已经不在服 ...

  7. Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十三):配置中心(Config、Bus)

    在线演示 演示地址:http://139.196.87.48:9002/kitty 用户名:admin 密码:admin 技术背景 如今微服务架构盛行,在分布式系统中,项目日益庞大,子项目日益增多,每 ...

  8. Spring Cloud学习 之 Spring Cloud Ribbon 重试机制及超时设置不生效

    今天测了一下Ribbon的重试跟超时机制,发现进行的全局超时配置一直不生效,配置如下: ribbon: #单位ms,请求连接的超时时间,默认1000 ConnectTimeout: 500 #单位ms ...

  9. Spring Cloud启动应用时指定IP或忽略某张网卡配置

    说明:分布式应用部署到服务上,由于服务器可能存在多张网卡,造成IP地址不准的问题. 解决方法: 1.直接添加忽略某张网卡的配置: spring.cloud.inetutils.ignored-inte ...

随机推荐

  1. centos设置服务开机启动失败问题

    1.安装某服务设置开机启动的时候报错 [root@node1 ~]# systemctl enable lvm2-lvmetad.serviceThe unit files have no [Inst ...

  2. cartographer 最新版安装测试

    在官网的基础上稍加修改,但保证代码都是最新的 我的系统配置: Debian9 strech,  ROS lunar 该方法对 ubuntu 系列操作系统以及其他ROS版本同样适用. 1.  安装依赖库 ...

  3. 论文笔记:Rich feature hierarchies for accurate object detection and semantic segmentation

    在上计算机视觉这门课的时候,老师曾经留过一个作业:识别一张 A4 纸上的手写数字.按照传统的做法,这种手写体或者验证码识别的项目,都是按照定位+分割+识别的套路.但凡上网搜一下,就能找到一堆识别的教程 ...

  4. V4L2 API详解 <二> Camera详细设置【转】

    转自:http://blog.sina.com.cn/s/blog_602f87700101bf36.html 作者: Sam (甄峰)  sam_code@hotmail.com   Camera的 ...

  5. C++游戏开发需要阅读的书籍

    如果要自学游戏程序开发的话,可以看看下面的,呵呵. 游戏开发资料(PDF书都是中文版的,非英文,很多是本人自己扫描制作,从未网上发布过,所以独家啦):  1.Gamebryo 2.2游戏引擎(盛大.腾 ...

  6. 【原创】Linux基础之gz文件相关操作

    gz文件不需要解压即可进行相关操作 $ zcat test.log.gz $ zmore test.log.gz $ zless test.log.gz $ zgrep '1.2.3.4' test. ...

  7. [HTTP]HTTP 中的 Transfer-Encoding 报文头

    一.背景: 持续连接的问题:对于非持续连接,浏览器可以通过连接是否关闭来界定请求或响应实体的边界:而对于持续连接,这种方法显然不奏效.有时,尽管我已经发送完所有数据,但浏览器并不知道这一点,它无法得知 ...

  8. 基于官方mysql镜像构建自己的mysql镜像

    参考文章:https://www.jb51.net/article/115422.htm搭建步骤 1.首先创建Dckerfile: 1 2 3 4 5 6 7 8 9 10 11 12 FROM my ...

  9. Tp5自定义标签

    'taglib_build_in'    => 'cx,tags', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序 <?php namespace thin ...

  10. 1)requests模块

    一:requests 介绍 requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装, 从而使得Pyt ...