這是一個簡單的例子,hystrix的參數配置因為比較多會在之後寫出來。可以先參考,跑起來一個小例子。
1、概念:Hystrix 熔斷機制
當調用服務出現問題之後整個系統會出現錯誤的提示信息,而這個時候如果不想出現這樣的錯誤信息,而希望替換一個錯誤的內容。
一個服務掛了後續的服務跟著不能用了,這就是雪崩效應
對於熔斷技術的實現需要考慮以下幾種情況:
· 出現錯誤之後可以 fallback 錯誤的處理信息;
· 如果要結合 Feign 一起使用的時候還需要在 Feign(客戶端)進行熔斷的配置(feign以後再寫)。
Hystrix 基本配置
package cn.study.microcloud.rest;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import cn.study.microcloud.service.IDeptService;
import cn.study.vo.Dept;
@RestController
public class DeptRest {
@Resource
private IDeptService deptService;
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod="getFallback") // 如果當前調用的get()方法出現了錯誤,則執行fallback
public Object get(@PathVariable("id") long id) {
Dept vo = this.deptService.get(id) ; // 接收數據庫的查詢結果
if (vo == null) { // 數據不存在,假設讓它拋出個錯誤
throw new RuntimeException("部門信息不存在!") ;
}
return vo ;
}
public Object getFallback(@PathVariable("id") long id) { // 此時方法的參數 與get()一致
Dept vo = new Dept() ;
vo.setDeptno(999999L);
vo.setDname("【ERROR】Microcloud-Dept-Hystrix"); // 錯誤的提示
vo.setLoc("DEPT-Provider");
return vo ;
}
}
如果 get()方法拋出錯誤信息,會默認使用“@HystrixCommand”註解之中配置好的 fallbackMethod 調用類中的指定方法,這裡配置的是getFallback()方法
啟動類中配置
package cn.study.microcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableHystrixDashboard // hystrix的監控
public class Dept_8001_StartSpringCloudApplication {
public static void main(String[] args) {
SpringApplication.run(Dept_8001_StartSpringCloudApplication.class, args);
}
}
HystrixDashboard服務監控配置
監控地址
http://127.0.0.1:9001/hystrix; 打開網頁
在第一個輸入框中輸入
http://127.0.0.1:9001/hystrix.stream;
然後點擊跳轉按鈕即可
這樣就OK了
閱讀更多 有志者1281 的文章