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

断路器简介

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

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

此时若库存服务响应缓慢,会直接导致订单服务的线程被挂起,以等待库存申请服务的响应,在漫长的等待之后用户会因为请求库存失败而得到创建订单失败的结果。

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

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

快速入门

首先,添加断路器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

转载于:https://my.oschina.net/u/2450666/blog/1499040

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值