服务降级和服务熔断的区别_Spring Cloud 熔断 隔离 服务降级
一、hystrix
hystrix主要实现熔断和隔离,限流的功能基本没有,通过fallback实现服务降级和快速失败。核心是HystrixCommand。配置主要包含exection、fallback、circuitBreaker、metric、threadPool等。
二、加入依赖包
org.springframework.cloud spring-cloud-starter-hystrix 1.4.7.RELEASE
com.netflix.hystrix hystrix-javanica
三、在application.yml中加入配置
feign: hystrix: enabled: truehystrix:command:default:execution:timeout:enabled: trueisolation:strategy: THREADthread:timeoutInMilliseconds: 8000interruptOnTimeout: trueinterruptOnCancel: truefallback:enabled: trueisolation: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、在浏览器中多次刷新如下地址,导致熔断打开

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

3、过一会,过了休眠期,再访问正常路径,可以正常访问
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
