天天看點

SpringCloud學習筆記(四) 斷路器Hystrix

1. 什麼是斷路器(Hystrix)

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

2. Ribbon下如何使用Hystrix

在之前的consumer-ribbon中進行修改,映入Hystrix依賴

spring-cloud-starter-netflix-hystrix

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
           

在啟動類上添加注解

@EnableHystrix

,表示開啟斷路器功能

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class ConsumerRibbonApplication {

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

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

修改HelloService類的方法,在調用服務的方法上添加

@HystrixCommand(fallbackMethod = "fail")

,表示如果服務調用失敗則通路fail方法,所有也許在該類中建立一個fail方法。

@Service
public class HelloService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fail")
    public String sayHello(String name){
        String forObject = restTemplate.getForObject("http://PROVIDER/hello?name={name}", String.class, name);
        return forObject;
    }

    public String fail(String name){
        return "hello "+name+", Access failure.";
    }
}
           

測試:

1.啟動eureka服務

2.啟動兩個provider服務,端口分别是8081,8082

3.啟動consumer-ribbon

4.調用

http://localhost:8083/hello

SpringCloud學習筆記(四) 斷路器Hystrix
SpringCloud學習筆記(四) 斷路器Hystrix

5.關閉8081的服務,再次通路,8082可以正常通路,8081通路失敗調用了fail方法

SpringCloud學習筆記(四) 斷路器Hystrix
SpringCloud學習筆記(四) 斷路器Hystrix

3. Feign中如何使用Hystrix

修改consumer-feign工程,同樣加入依賴

spring-cloud-starter-netflix-hystrix

,然後在配置檔案中開啟feign的hystrix

spring:
  application:
    name: consumer-feign

server:
  port: 8084

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka
feign:
  hystrix:
    enabled: true #開啟hystrix
           

修改HelloService,在

@FeignClient

注解中添加

fallback

屬性值,

@FeignClient(value = "provider",fallback = HelloServiceHystrix.class)

@FeignClient(value = "provider",fallback = HelloServiceHystrix.class)
public interface HelloService {

    @GetMapping("/hello")
    String sayHello(@RequestParam("name") String name);
}
           

所有還需要建立一個HelloServiceHystrix類,實作斷路器功能,該類需要繼承HelloService接口,實作其中方法,作為斷路處理方法,并将該類注入到spring容器中

@Component
public class HelloServiceHystrix implements HelloService {
    @Override
    public String sayHello(String name) {
        return "hello "+name+", Access failure.";
    }
}
           

測試:

1.啟動eureka服務

2.啟動consumer-feign

3.通路

http://localhost:8084/hello?name=xinfeng

SpringCloud學習筆記(四) 斷路器Hystrix

我們并沒有開啟provider項目,所有通路不到它提供的服務,這時就執行了斷路執行的斷路器的方法。

繼續閱讀