spring cloud学习之六: Hystrix(熔断器)

在微服务架构中,我们通常会将一个大系统拆分成多个小服务,各个服务之间通过服务注册与订阅的方式进行依赖,依赖通过远程调用(RPC)的方式执行。通过这种方式,可能就会因为网络或者服务本身的问题而导致调用延迟或故障,就会造成调用者的服务延迟,当持续中断、无法提供服务,就会造成整个系统的崩溃,因此引出Hystrix–服务容错保护机制。
Spring Cloud Hystrix 实现了断路器、线程隔离等一系列服务保护功能,是基于Netflix Hystrix实现的。 Hystrix具备服务降级服务熔断线程和信号隔离、请求缓存、请求合并以及服务监控等功能。
在该篇文章中只介绍springcloud 如何集成Hystrix及使用方法,实现服务降级。之后在不断的学习中进行补充。
创建两个spring boot 基础工程,集成Eureka-client、config-client、ribbon等依赖,如有不懂,请看之前的文章、或者留言。
添加Hystrix依赖
pom.xml

<!--熔断器-->
		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
			<version>1.3.5.RELEASE</version>
		</dependency>

启动类添加注解,开启Hystrix功能支持

@EnableHystrix //包含了 @EnableCircuitBreaker 注解
或
@EnableCircuitBreaker

bootstrap.properties 配置

#服务端口号
server.port=8181
#服务访问路径
server.context-path=/clientone
#应用名称,用于服务注册及访问
spring.application.name=clientone

#配置注册eureka地址
eureka.client.service-url.defaultZone=http://192.168.2.83:7081/eureka/
#配置-配置文件
开启通过服务访问config
spring.cloud.config.discovery.enabled=true
#config服务名
spring.cloud.config.discovery.service-id=config-server
#仓库中通过profile定位配置文件
spring.cloud.config.profile=dev
#配置仓库文件分支
spring.cloud.config.label=dev

##开启配置文件的快速失败与重试
spring.cloud.config.fail-fast=true
##配置重试参数,一下配置的是默认值
#最大重试次数
spring.cloud.config.retry.max-attempts=6
#重试间隔,毫秒
spring.cloud.config.retry.initial-interval=1000
#重试乘数,下次重试的间隔 1.1*当前重试时间
spring.cloud.config.retry.multiplier=1.1
#最大重试时间,毫秒
spring.cloud.config.retry.max-interval=2000

##ribbon重试
#开启服务重试机制
spring.cloud.loadbalancer.retry.enabled=true
#请求连接超时时间,默认250
ribbon.ConnectTimeout=2000
#请求处理的超时时间,默认1000
ribbon.ReadTimeout=6000
#对虽有请求都进行重试,默认 true
ribbon.OkToRetryOnAllOperations=true
#切换实例的重试次数,默认 2
ribbon.MaxAutoRetriesNextServer=2
#对当前实例的重试次数,默认 1
ribbon.MaxAutoRetries=1

#断路器超时时间,默认为2000,该时间要大于ribbon的时间,否则会触发重试机制
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000


#开启热启动
spring.devtools.restart.enabled=true

第一个服务创建一个访问接口

@RestController
@RequestMapping("/ribbon")
public class TestRibbon {

    @Autowired
    private DiscoveryClient discoveryClient;


    /**
     * @author:XingWL
     * @description:测试接口
     * @date: 2019/2/22 10:29
     */
    @ResponseBody
    @RequestMapping(value = "/testRibbonProducer",method = RequestMethod.GET)
    public String testRibbon(){
        ServiceInstance instance=discoveryClient.getLocalServiceInstance();
        String hostMsg="";
        try {
            long time= new Random().nextInt(3000);
            System.out.println("=====休眠时长:"+time+"=====");
            Thread.sleep(time);
            hostMsg= "Producer: host-"+instance.getHost()+",service_id-"+instance.getServiceId()+",Url-"+instance.getUri();
        } catch (Exception e) {
            e.printStackTrace();
            hostMsg="异常";
        }
        return hostMsg;
    }
}

第二个服务创建一个接口

@RestController
@RequestMapping("/ribbon")
public class TestRibbon {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private ServiceHystrix serviceHystrix;


    /**
     * @author:XingWL
     * @description:测试接口
     * @date: 2019/2/22 10:29
     */
    @ResponseBody
    @RequestMapping(value = "/testRibbonProducer",method = RequestMethod.GET)
    public String testRibbon(){
        ServiceInstance instance=discoveryClient.getLocalServiceInstance();
        String hostMsg="";
        try {
            hostMsg= "Producer: host-"+instance.getHost()+",service_id-"+instance.getServiceId()+",Url-"+instance.getUri();
        } catch (Exception e) {
            e.printStackTrace();
            hostMsg="异常";
        }
        return hostMsg;
    }

    /**
     * @author:XingWL
     * @description:测试接口
     * @date: 2019/2/22 10:29
     */
    @ResponseBody
    @RequestMapping(value = "/testHystrix",method = RequestMethod.GET)
    public String testHystrix(){
        return serviceHystrix.testHystrix();
    }

}

第二个服务添加一个服务类

@Service
public class ServiceHystrix {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallbackTest")
    public String testHystrix(){
        return restTemplate.getForEntity("http://CLIENTONE/clientone/ribbon/testRibbonProducer",String.class).getBody();
    }

    public String fallbackTest(){
        return "Hystrix -- fallback";
    }

}

使用注解 @HystrixCommand(fallbackMethod = “fallbackTest”)
其中,fallbackMethod的值为同一个类下的方法,Hystrix默认超时时间为 2000ms
通过第二个服务去调用第一个服务的接口结果如图:
在这里插入图片描述
在这里插入图片描述
当被调用的服务发生故障或者延迟超时时,会通过 @HystrixCommand(fallbackMethod = “fallbackTest”)进行服务降级,返回处理结果。

断路器

isOpen()是用来判断断路器 关闭/打开的状态,
一个滚动时间窗内(10s),请求总数(QPS–默认-20)在请求数的范围内就为
fasle
,错误百分比的阀值默认为50%。
allowRequest()–判断请求是否被允许
当断路器处于打开状态时,会判断断开的时间戳+配置中的 circuitBreakerSleepWindowInMilliseconds时间是否小于当前时间(默认5s),是的话,就将当前时间更新到记录断路器打开的时间对象circuitOpenedOrLastTestedTime中,并且允许此次请求,在休眠时间到达之后,将再次允许请求尝试,此时断路器处于半开状态,若此时请求继续失败,断路器将再次打开。所以**allowRequest()isOpen()**配合实现断路器的打开、关闭状态的切换。
**依赖隔离’**之 舱壁模式
Hystrix使用该模式实现线程池隔离(为每个依赖服务提供一个独立的线程池,默认大小为10)。

持续更新中。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值