spring cloud Hystix熔断机制--基本熔断配置和Fegin client熔断配置
所谓的熔断机制和日常生活中见到电路保险丝是非常相似的,当出现了问题之后,保险丝会自动烧断,以保护我们的电器, 那么如果换到了程序之中呢?
当现在服务的提供方出现了问题之后整个的程序将出现错误的信息显示,而这个时候如果不想出现这样的错误信息,而希望替换为一个错误时的内容。

一个服务挂了后续的服务跟着不能用了,这就是雪崩效应
对于熔断技术的实现需要考虑以下几种情况:
· 出现错误之后可以 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熔断配置的更多相关文章
- Spring Cloud Eureka 自我保护机制
Eureka Server 在运行期间会去统计心跳失败比例在 15 分钟之内是否低于 85%,如果低于 85%,Eureka Server 会将这些实例保护起来,让这些实例不会过期,但是在保护期内如果 ...
- spring cloud 的自我保护机制
spring cloud 的自我保护机制定义: 自我保护模式是:在出现网络异常波动的情况下,使用自我保护模式使eureka 集群更加健壮,稳定. 自我保护机制是:在15分钟内客户端没有雨注册中心发生心 ...
- Spring Cloud Eureka 自我保护机制实战分析
前些天栈长在Java技术栈微信公众号分享过 Spring Cloud Eureka 的系列文章: Spring Cloud Eureka 自我保护机制 Spring Cloud Eureka 常用配置 ...
- Spring Cloud Gateway重试机制
前言 重试,我相信大家并不陌生.在我们调用Http接口的时候,总会因为某种原因调用失败,这个时候我们可以通过重试的方式,来重新请求接口. 生活中这样的事例很多,比如打电话,对方正在通话中啊,信号不好啊 ...
- spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略
spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略 某电子商务网站在一个黑色星期五 ...
- Spring Cloud 请求重试机制核心代码分析
场景 发布微服务的操作一般都是打完新代码的包,kill掉在跑的应用,替换新的包,启动. spring cloud 中使用eureka为注册中心,它是允许服务列表数据的延迟性的,就是说即使应用已经不在服 ...
- Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十三):配置中心(Config、Bus)
在线演示 演示地址:http://139.196.87.48:9002/kitty 用户名:admin 密码:admin 技术背景 如今微服务架构盛行,在分布式系统中,项目日益庞大,子项目日益增多,每 ...
- Spring Cloud学习 之 Spring Cloud Ribbon 重试机制及超时设置不生效
今天测了一下Ribbon的重试跟超时机制,发现进行的全局超时配置一直不生效,配置如下: ribbon: #单位ms,请求连接的超时时间,默认1000 ConnectTimeout: 500 #单位ms ...
- Spring Cloud启动应用时指定IP或忽略某张网卡配置
说明:分布式应用部署到服务上,由于服务器可能存在多张网卡,造成IP地址不准的问题. 解决方法: 1.直接添加忽略某张网卡的配置: spring.cloud.inetutils.ignored-inte ...
随机推荐
- 存在Settings数据在手机系统中的位置
旧版本Android,将settings数据存在数据库中,{system, secure, global} 对应的是 /data/data/com.android.providers.settings ...
- 使用SQL*Plus连接数据库
About SQL*Plus SQL*Plus is the primary command-line interface to your Oracle database. You use SQL*P ...
- Python 模拟鼠键
让python 自动操作桌面或应用窗口,点击,滑动鼠标,输入文字等 # coding=utf-8 from pymouse import PyMouse from pykeyboard import ...
- Boost 序列化
原文链接: https://blog.csdn.net/qq2399431200/article/details/45621921 1. 编译器 gcc, boost 1.55 2.1第一个简单的例子 ...
- Python学习笔记-条件语句
学习代码如下 flag=False name = raw_input("请输入:"); if name == '羊爸爸': flag=True print 'Welcome Hom ...
- Angular 创建组件
创建组件 0 命令创建 1 创建组件 定义hello.component.ts组件 在app.module.ts中引用并添加到declarations声明中 在app.component.html中使 ...
- C#代码处理前台html标签拼接
之前一篇文章是写,JavaScript处理特殊字符拼接时截断问题.最近在处理公司老软件兼容性升级时碰到的一个类似的问题,这次是后台拼接字符串,前台.aspx页面显示的.中间走了两次弯路,在此记录一下. ...
- 007grafana监控时间戳转换
一. https://d.jyall.me/dashboard-solo/db/soloview?panelId=1&var-metrics=stats.gauges.zookeeper.mo ...
- why should the parameter in copy construction be a reference
if not, it will lead to an endless loop!!! # include<iostream> using namespace std; class A { ...
- ASP.NET Core之NLog使用
1.新建ASP.NET Core项目 1.1选择项目 1.2选择.Net版本 2. 添加NLog插件 2.1 通过Nuget安装 2.2下载相关的插件 3.修改NLog配置文件 3.1添加NLog配置 ...