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

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

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

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

· 出现错误之后可以 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. java基础梳理--朝花夕拾(二)

    1.Java语言语法规则和文件格式: 第一个Java程序:/** 第一个Java程序:控制台输出Hello world!*/public class Test{    //访问修饰符 class关键词 ...

  2. 前端-----css(1)

    css概述 CSS是Cascading Style Sheets的简称,中文称为层叠样式表,用来控制网页数据的表现,可以使网页的表现与数据内容分离. css知识点 注释 /* 注释内容 */ css四 ...

  3. 20165231 2017-2018-2 《Java程序设计》第1周学习总结

    本周学习的是一些java简单的基本编译,反编译和解释器.然后学习使用git了上传到git@osc进行代码托管,git是初学的,需要建立库然后远程上传代码,如果建立失败或者因为种种缘故无法上传的可以一个 ...

  4. Java9 新特性

    Java9中的9个新特性 1. Java 平台级模块系统 2. Linking 3. JShell: 交互式 Java REPL 4. 改进的 Javadoc 5. 集合工厂方法 6. 改进的 Str ...

  5. 【转】python之random模块分析(一)

    [转]python之random模块分析(一) random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): ...

  6. Python-集合的常用操作

    #!/usr/bin/env python # -*- coding:utf- -*- # Author:Irving list_1 = [,,,,,,,] list_1 = set(list_1) ...

  7. Git学习笔记02-创建版本库

    版本库就是一个目录,这个目录里面的所有文件都会被Git管理,每个文件的修改,删除都能追踪.以便在某个时刻追踪历史记录,或者还原 路径切换,查看文件命令和linux差不多,cd 文件路径  ls查看路径 ...

  8. NodeJS基础教程

    关于 本书致力于教会你如何用Node.js来开发应用,过程中会传授你所有所需的“高级”JavaScript知识.本书绝不是一本“Hello World”的教程. 状态 你正在阅读的已经是本书的最终版. ...

  9. linux 提高代码质量的工具

    很多IT公司对于软件开发都有严格的分工,这包括设计.测试.服务支持等等.但是,我一直都认为只有开发者才是真正对软件质量负责的人.没有好的软件设计,软件质量基本上是无从谈起.当然,要做到这一点是需要额外 ...

  10. python第13天

    装饰器 装饰器本质上就是一个python函数,他可以让其他函数在不需要做任何改动的前提下,增加额外的功能,装饰器的返回值也是一个函数对象. 装饰器的应用场景:比如插入日志,性能测试,事务处理,缓存等等 ...