1. 程式人生 > >spring-cloud(四)斷路器(Hystrix)(Finchley版本)

spring-cloud(四)斷路器(Hystrix)(Finchley版本)

在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以相互呼叫(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign來呼叫。為了保證其高可用,單個服務通常會叢集部署。由於網路原因或者自身的原因,服務並不能保證100%可用,如果單個服務出現問題,呼叫這個服務就會出現執行緒阻塞,此時若有大量的請求湧入,Servlet容器的執行緒資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重後果,這就是服務故障的“雪崩”效應。

為了解決這個問題,業界提出了斷路器模型。
Netflix開源了Hystrix元件,實現了斷路器模式,SpringCloud對這一元件進行了整合。 在微服務架構中,一個請求需要呼叫多個服務是非常常見的,如下圖:

較底層的服務如果出現故障,會導致連鎖故障。當對特定的服務的呼叫的不可用達到一個閥值(Hystric 是5秒20次) 斷路器將會被開啟。

斷路開啟後,可用避免連鎖故障,fallback方法可以直接返回一個固定值

啟動eureka-server 啟動eureka-client 

1在ribbon中新增斷路器

在ribbon-server服務pom.xml檔案中新增對hystrix的依賴

        <!--熔斷器-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

在啟動類中新增@EnableHystrix註解

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class RibbonServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(RibbonServerApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

改造HelloService類,在hello方法上加上@HystrixCommand註解。該註解對該方法建立了熔斷器的功能,並指定了fallbackMethod熔斷方法,熔斷方法直接返回了一個字串,字串為"出現錯誤了!"

@Service
public class HelloService {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod="error")
    public String hello(String name){
        return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
    }
    public String error(String name){
        return "出現錯誤了!";
    }
}

啟動ribbon

正常訪問http://localhost:8764/hi?name=123

此時如果停止eureka-client服務 再次訪問發現快速執行error方法

 

2Feign中使用斷路器

Feign是自帶斷路器的,在D版本的Spring Cloud之後,它沒有預設開啟。需要在配置檔案中配置開啟它,在配置檔案加以下程式碼:

application.properties檔案中新增

feign.hystrix.enabled=true

Feign介面Hello上加@FeignClient註解

@FeignClient(value = "eureka-client",fallback = HelloHystrix.class)
public interface Hello {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    public String selectOneTohello(@RequestParam(value="name") String name);
}

新增HelloHystrix實現Hello介面

@Component
public class HelloHystrix implements Hello{
    @Override
    public String selectOneTohello(String name) {
        return "出錯了!";
    }
}

正常訪問http://localhost:8765/hi?name=123

此時如果停止eureka-client服務 再次訪問發現快速執行error方法