(各位看官老爺大家好,不知道什麼原因,我在某次編輯後,文章的圖就消失了,添加不上去,可能會影響各位的閱讀,在此緻以歉意!)
一.斷路器簡介
較底層的服務如果出現故障,會導緻連鎖故障。當對特定的服務的調用的不可用達到一個閥值(Hystric 是5秒20次) 斷路器将會被打開。
斷路打開後,可用避免連鎖故障,fallback方法可以直接傳回一個固定值。
二.啟動工程
啟動eureka-server 工程;啟動service-hi工程,它的端口為8762
三.在ribbon使用斷路器
改造serice-ribbon 工程的代碼,首先在pox.xml檔案中加入spring-cloud-starter-hystrix的起步依賴:
org.springframework.cloud
spring-cloud-starter-hystrix
1.1.3.RELEASE
com.netflix.hystrix
hystrix-javanica
RELEASE
在程式的啟動類ServiceRibbonApplication 加@EnableHystrix注解開啟Hystrix
改造HelloService類,在hiService方法上加上@HystrixCommand注解。該注解對該方法建立了熔斷器的功能,并指定了fallbackMethod熔斷方法,熔斷方法直接傳回了一個字元串,字元串為”hi,”+name+”,sorry,error!”,
hi forezp,i am from port:8762
hi,forezp!sorry,error!
這就說明當 service-hi 工程不可用的時候,service-ribbon調用 service-hi的API接口時,會執行快速失敗,直接傳回一組字元串,而不是等待響應逾時,這很好的控制了容器的線程阻塞。
四.Feign中使用斷路器
Feign是自帶斷路器的,在D版本的Spring Cloud中,它沒有預設打開。需要在配置檔案中配置打開它,在配置檔案加以下代碼:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon
Feign是自帶斷路器的,在D版本的Spring Cloud中,它沒有預設打開。需要在配置檔案中配置打開它,在配置檔案加以下代碼:
feign:
hystrix:
enabled: true
基于service-feign工程進行改造,隻需要在FeignClient的SchedualServiceHi接口的注解中加上fallback的指定類就行了:
@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)
public interface SchedualServiceHi {
RequestMapping(value = "/hi",method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
SchedualServiceHiHystric需要實作SchedualServiceHi 接口,并注入到Ioc容器中,代碼如下:
@Component
public class SchedualServiceHiHystric implements SchedualServiceHi {
@Override
public String sayHiFromClientOne(String name) {
return "sorry "+name;
}
}
啟動四servcie-feign工程,浏覽器打開http://localhost:8765/hi?name=forezp,注意此時service-hi工程沒有啟動,網頁顯示:
sorry forezp
打開service-hi工程,再次通路,浏覽器顯示:
>hi forezp,i am from port:8762
這證明斷路器起到作用了。
五.Hystrix Dashboard (斷路器:Hystrix 儀表盤)
首選在pom.xml引入spring-cloud-starter-hystrix-dashboard的起步依賴:
org.springframework.boot
spring-boot-starter-actuator
1.1.3.RELEASE
org.springframework.cloud
spring-cloud-starter-hystrix-dashboard
1.1.3.RELEASE
在主程式啟動類中加入@EnableHystrixDashboard注解,開啟hystrixDashboard:
@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrixDashboard
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}

此時會出現監控界面: