(七)SpringBoot+SpringCloud —— 集成断路器

断路器简介

在一个项目中,系统可能被拆分红多个服务,例如用户、订单和库存等。java

这里存在这服务调用服务的状况,例如,客户端调用订单服务,订单服务又调用库存服务。git

此时若库存服务响应缓慢,会直接致使订单服务的线程被挂起,以等待库存申请服务的响应,在漫长的等待以后用户会由于请求库存失败而获得建立订单失败的结果。github

若是在高并发下,因这些挂起的线程在等待库存服务的响应而未能得到释放,会似的后续到来的请求被阻塞,最终致使订单服务也不可用。web

在分布式架构中,断路器模式的做用也是相似的,当某个服务单元发生故障以后,经过断路器的故障监控,向调用方返回一个错误响应,而不是漫长的等待。spring

快速入门

首先,添加断路器hystrix的依赖。缓存

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

接着在工程的主类,添加注解@EnableCircuitBreaker:架构

package cn.net.bysoft.owl.bookstore.web.console;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class OwlBookstoreWebConsoleApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(OwlBookstoreWebConsoleApplication.class, args);
    }
}

接着,就能够使用断路器了,能够添加@HystrixCommand注解,对调用服务的方法进行修饰:并发

@HystrixCommand(fallbackMethod = "findByIdFallback")
	public User findById(Long id) {
		UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://SERVICE-USER/users/{id}").build()
				.expand(id).encode();
		URI uri = uriComponents.toUri();
		return restTemplate.getForObject(uri, User.class);
	}
	
	public User findByIdFallback(Long id) {
		return null;
	}

fallbackMethod是服务发生异常时,回调的降级处理函数,该函数的参数和返回值要与调用函数一致。分布式

断路器的默认超时时间为2000毫秒。当被断路器修饰的函数执行超过这个值,将触发断路器的服务降级,该参数是能够设置的。函数

断路器配置

全局配置属性:hystrix.[attr].default.

实例配置属性:hystrix.[attr].[key].

execution配置

  1. Command Properties
    1. Execution
      1. execution.isolation.strategy (执行的隔离策略)
      2. execution.isolation.thread.timeoutInMilliseconds(执行的超时时间)
      3. execution.timeout.enabled(是否启用超时时间)
      4. execution.isolation.thread.interruptOnTimeout(超时发生后是否要中断该服务)
      5. execution.isolation.thread.interruptOnCancel(执行被取消后是否要中断该服务)
      6. execution.isolation.semaphore.maxConcurrentRequests(当最大并发达到该值,后续的请求会被拒绝)
    2. Fallback
      1. fallback.isolation.semaphore.maxConcurrentRequests(fallback方法执行的最大并发请求数,当达到最大,后续的请求将会被拒绝并抛出异常)
      2. fallback.enabled(服务降级策略是否启用)
    3. Circuit Breaker
      1. circuitBreaker.enabled (断路器开关)
      2. circuitBreaker.requestVolumeThreshold (断路器请求阈值)
      3. circuitBreaker.sleepWindowInMilliseconds(断路器休眠时间)
      4. circuitBreaker.errorThresholdPercentage(断路器错误请求百分比)
      5. circuitBreaker.forceOpen(断路器强制开启)
      6. circuitBreaker.forceClosed(断路器强制关闭)
    4. Metrics
      1. metrics.rollingStats.timeInMilliseconds(滚动时间窗长度,毫秒级)
      2. metrics.rollingStats.numBuckets(滚动时间窗统计指标信息时划分“桶”的数量)
      3. metrics.rollingPercentile.enabled(对命令执行的延迟是否使用百分位数来跟踪和计算)
      4. metrics.rollingPercentile.timeInMilliseconds(设置百分位统计的滚动窗口的持续时间)
      5. metrics.rollingPercentile.numBuckets(设置百分位统计滚动窗口中使用“桶”的数量)
      6. metrics.rollingPercentile.bucketSize(设置在执行过程当中每一个“桶”中保留的最大执行次数)
      7. metrics.healthSnapshot.intervalInMilliseconds(采集健康快照的间隔等待时间)
    5. Request Context
      1. requestCache.enabled(是否启用缓存)
      2. requestLog.enabled(执行的时间是否打印到日志)
  2. Collapser Properties
    1. maxRequestsInBatch(请求合并批处理中容许的最大请求数)
    2. timerDelayInMilliseconds(批处理过程当中每一个命令延迟的时间,毫秒级)
    3. requestCache.enabled(是否开启请求缓存)
  3. Thread Pool Properties
    1. coreSize(线程池大小)
    2. maxQueueSize(最大队列数量)
    3. queueSizeRejectionThreshold (队列大小拒绝阈值)
    4. metrics.rollingStats.timeInMilliseconds(滚动时间窗的长度,毫秒级)
    5. metrics.rollingStats.numBuckets(滚动时间窗被划分的数量)

Github

https://github.com/XuePeng87/owl-bookstore

相关文章
相关标签/搜索