服务降级和服务熔断的区别_Spring Cloud 熔断 隔离 服务降级

一、hystrix

hystrix主要实现熔断和隔离,限流的功能基本没有,通过fallback实现服务降级和快速失败。核心是HystrixCommand。配置主要包含exection、fallback、circuitBreaker、metric、threadPool等。

二、加入依赖包

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-hystrix</artifactId>
	<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
	<groupId>com.netflix.hystrix</groupId>
	<artifactId>hystrix-javanica</artifactId>
</dependency>

三、在application.yml中加入配置

feign: 
  hystrix: 
    enabled: true

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          strategy: THREAD
          thread:
            timeoutInMilliseconds: 8000
            interruptOnTimeout: true
            interruptOnCancel: true
      fallback:
        enabled: true
        isolation:
          semaphore:
            maxConcurrentRequests: 2

四、在访问接口上实现熔断、隔离和服务降级

@HystrixCommand(commandKey = "circuitBreakerCommand",threadPoolKey = "circuitBreakerPool",fallbackMethod = "circuitBreakerFallbackMethod",
			commandProperties = {
					@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
					@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
					@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
					@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
					}, 
		    threadPoolProperties = {
					@HystrixProperty(name = "coreSize", value = "5") 
					})
    @GetMapping("/circuitBreakerHello/{id}")
	public String circuitBreakerHello(@PathVariable("id") int id) {
    	if(id==2){
            throw new RuntimeException("exception");
        }
        return "sucessful execution" ;
	}
    public String circuitBreakerFallbackMethod(int id) {
    	return "param "+id+" is wrong. circuitBreaker has been valid";
}

五、启动类上添加@EnableHystrix

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
@MapperScan("com.sboot.dao")
public class ConsulConsumerApplication {
	public static void main(String[] args) {
		SpringApplication.run(ConsulConsumerApplication.class, args);
	}
}

六、测试

1、在浏览器中多次刷新如下地址,导致熔断打开

7a405bbe802cf4bfc439d8be19944010.png

2、当访问正常得路径http://localhost:8082/circuitBreakerHello/1,也走服务降级:

93d5602fb6fb217cb9d998bad2c37ab3.png

3、过一会,过了休眠期,再访问正常路径,可以正常访问

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值