springcloud之Hystrix熔断器

雪崩效应

在分布式系统中,各个服务相互调用相互依赖,如果某个服务挂了,很可能导致其他调用它的一连串服务也挂掉或者在不断等待耗尽服务器资源,这种现象称之为服务器雪崩效应

熔断机制

未来防止系统雪崩,熔断机制必不可少,就是当一个服务挂掉后,调用它的服务能快速熔断,不再耗费资源,快速失败并提供回退方案

Hystrix

Hystrixspring cloud全家桶的Circuit Breaker熔断器组件,提供了熔断器功能,能够阻止联动故障,并提供故障的解决方案,提供系统弹性;

maven依赖
!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix --
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-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();
}
最新回复(0)
/jishuIYbIeAebaHorQr2skd01THvzQUfhpWf8XPuo7w_3D_3D
8