雪崩效應
在分佈式系統中,各個服務相互調用相互依賴,如果某個服務掛了,很可能導致其他調用它的一連串服務也掛掉
或者在不斷等待
中耗盡服務器資源
,這種現象稱之爲服務器雪崩效應
;
熔斷機制
未來防止系統雪崩,熔斷機制必不可少,就是當一個服務掛掉後,調用它的服務能快速熔斷,不再耗費資源,快速失敗
並提供回退方案
;
Hystrix
Hystrix
是spring cloud
全家桶的Circuit Breaker
熔斷器組件,提供了熔斷器功能,能夠阻止聯動故障,並提供故障的解決方案,提供系統彈性;
maven依賴
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
application.yml
在配置文件中開啓熔斷器
#開啓熔斷器開關
feign:
hystrix:
enabled: true
@EnableHystrix啓動Hystrix
SpringBoot啓動類中增加 @EnableHystrix 註解和bean
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
@EnableFeignClients
public class SpringCloudApplication
{
public static void main(String[] args)
{
SpringApplication.run(application.class);
}
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
熔斷器類
增加熔斷器類,實現Feign的接口
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
public class FUserServiceHystrix implements FUserService
{
@RequestMapping("/user/hello")
@Override
public String hello()
{
return "對不起,user服務不可達,請稍後再試!";
}
}
熔斷器配置類
增加熔斷器配置類FeignConfig
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
public class FeignConfig {
@Bean
public Retryer feignRetryer() {
/*
* 參數說明:
* 第一個> 重試間隔爲100毫秒
* 第二個> 最大重試時間爲1秒
* 第三個> 最大重試次數爲5次
*/
return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 5);
}
}
增加fallback
在Feign接口註解中增加fallback,指向熔斷器類
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "user",configuration = FeignConfig.class,fallback = FUserServiceHystrix.class)
public interface FUserService
{
@RequestMapping("/user/hello")
public String hello();
}