本文共 2374 字,大约阅读时间需要 7 分钟。
SpringCloud(四):服务熔断保护-Hystrix【Finchley版】
为什么需要服务熔断保护?
在微服务架构中,我们将一个大的业务系统拆解成各种小的服务并且集群化部署,服务与服务之间通过RPC来进行调用,如果某个服务出现问题,导致线程阻塞了,外部进入大量请求,服务资源会在短时间内进行消耗,从而导致整个系统不可用,这就会出现一个雪崩效应,为了解决这个问题,我们就需要对服务进行熔断保护。
在 SpringCloud 中调用方式有 Ribbon+RestTemplate 和 Feign 两种方式,所以我们分别来看看这两种方式是如何用 Hystrix 来进行服务熔断的?
Ribbon+RestTemplate 结合 Hystrix 服务熔断
我们对ribbon-customer-server
进行改造
1、pom.xml
在 pom.xml 中引入 Hystrix 依赖
org.springframework.cloud spring-cloud-starter-netflix-hystrix
2、引导类
在引导类上添加@EnableCircuitBreaker
或者@EnableHystrix
注解,来开启 Hystrix
@SpringBootApplication@EnableDiscoveryClient//@EnableHystrix@EnableCircuitBreakerpublic class RibbonCustomerServerApplication { public static void main(String[] args) { SpringApplication.run(RibbonCustomerServerApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate(){ return new RestTemplate(); }}
3、Service 类
在service
类的hello
方法上添加@HystrixCommand
注解并且指定fallbackMethod ="helloError"
,我们在helloError
方法里编写默认返回数据
@HystrixCommand(fallbackMethod = "helloError") public String hello(){ return restTemplate.getForObject("http://hello-provider-service/hello",String.class); } public String helloError(){ return "服务器繁忙,请稍后再试!"; }
我们先不启动hello-provider-server
服务,直接启动ribbon-customer-server
,在浏览器里访问http://127.0.0.1:8087/hello
,我们将看到返回的为:
服务器繁忙,请稍后再试!
我们启动hello-provider-server
服务,再次多次访问http://127.0.0.1:8087/hello
,我们就会看到:
hello spring cloud ,i am port :8085
Feign 结合 Hystrix 服务熔断
Feign
已经结合了 Hystrix
,所以我们不需要额外引入配置,我们对feign-customer-service
项目进行改造,我们只要要编写一个HelloService接口的实现类,提供一些默认返回值就可以,并且在@FeignClient
上配置fallback
。
Service 改造
修改HelloService
接口,在@FeignClient
上添加fallback
参数
@FeignClient(value = "hello-provider-service",fallback = HelloHystrix.class)public interface HelloService { @GetMapping(path = "/hello") String hello();}
编写HelloHystrix
类
@Componentpublic class HelloHystrix implements HelloService { @Override public String hello() { return "系统繁忙,请稍后再试!!!"; }}
启动feign-customer-service
服务,访问http://127.0.0.1:8088/hello
,能够正常访问得到
hello spring cloud ,i am port :8085
关闭hello-provider-server
服务,再次访问http://127.0.0.1:8088/hello
,浏览器显示
系统繁忙,请稍后再试!!!
本文demo下载 :
转载地址:https://blog.csdn.net/z694644032/article/details/96875730 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!