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

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

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

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

· 出现错误之后可以 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. ReentrantLock(重入锁)的使用

    //效果和synchronized一样,都可以同步执行,lock方法获得锁,unlock方法释放锁public class MyService { private Lock lock = new Re ...

  2. ASP.NET - ADO.NET框架

    ADO.NET(ActiveX Data Objects) ADO.NET是一个COM组件库,用于在使用Microsoft技术的代码中访问数据库. SQL数据操作类 SqlConnection类(Sy ...

  3. python,<一>读取文件open()

    在实际操作中,我们经常会读取文件,这个时候python为我们提供了一个open()的方法,供我们读取文件,通过help(open),我们可以获取open的方法 f.close()关闭读取 f.read ...

  4. GridView position = 0重复加载的问题

    在做项目开发中,遇到GridView设置的adapter,adapter中包含异步加载图片的问题,因为gridView item的高度没有做限制,是自适应的,导致positon = 0会在加载时重复出 ...

  5. Android 6.0系统动态请求系统相机权限

    private static final int TAKE_PHOTO_REQUEST_CODE = 1; public static String takePhoto(Context context ...

  6. liunx之Centos6.8杀毒软件的安装

    作者:邓聪聪 为了防止服务器中病毒,安装了类似与Windowns的杀毒软件Clanav,过程如下 首先下载clamav的软件包,官方下载地址为http://www.clamav.net/downloa ...

  7. Flash硬件原理

    1.2.1. 什么是Flash Flash全名叫做Flash Memory,从名字就能看出,是种数据存储设备,存储设备有很多类,Flash属于非易失性存储设备(Non-volatile Memory ...

  8. 在 C# 中,(int) ,Int32.Parse() 和 Convert.toInt32() 三种方法的区别

    在 C# 中,(int),Int32.Parse() 和 Convert.toInt32() 三种方法有何区别? int 关键字表示一种整型,是32位的,它的 .NET Framework 类型为 S ...

  9. MySQL--表操作(约束条件foreign key关联表 多对1,多对多,1对1)

    一.所有数据都存放于一张表中的弊端:1.表的组织结构复杂不清晰2.浪费空间3.扩展性极差 解决方案:分表a.分表 + foreign key: 有硬性限制(关联表中的关联字段内容必须来自于被关联表), ...

  10. Vue -- 数据监听

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...