Spring Cloud微服務實戰---1.9.微服務架構容錯處理
阿新 • • 發佈:2018-12-13
在微服務架中,所有功能均通過微服務來提供,如果其中某個關鍵微服務出現問題,如響應時間過長,那麼所有呼叫這個微服務的微服務都會變慢,由於呼叫者微服務變慢,進一步會使其他更廣泛的微服務變慢,最終整個系統可能會因為一個微服務出現問題,而使整個微服務架構出現故障。為了防止這種現象的發生,我們可以使用Spring Cloud中的Hystrix元件。
Hystrix元件的原理是對每個微服務,都會維護其當前狀態,如果監測到某個微服務響應時間過長時,再有對這個微服務的訪問,就會執行報告該微服務不可用的錯誤響應程式,通過這個微服務呼叫者,該微服務當前不可用。這樣雖然有一些微服務呼叫會失敗,但是就不會出一個微服務失敗,拖慢整個系統的情況了。
我們首先需要在服務使用者專案中新增依賴,如下所示:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
在啟動類ProductConsumerApplication上新增@EnableCircuitBreaker註解:
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ProductConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ProductConsumerApplication.class, args);
}
}
接著我們需要新增一個新的Service類,用來處理對遠端微服務的訪問,如下所示:
@Service
public class ProductService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="callProductServiceError")
public String callPrudctService() {
ResponseEntity<String> resp = restTemplate.getForEntity("http://mse001/products",
String.class);
return resp.getBody();
}
public String callProductServiceError() {
return "{\"status\": \"Error\", \"errorCode\":1001, \"errorMsg\": \"測試Hystrix\"}";
}
}
在這裡我們定義了一個Service元件,將呼叫其他微服務的方法新增@HystrixCommand註解,其中的引數為當呼叫不能成功時,系統會自動呼叫的方法。當在實際應用中,如果被呼叫的微服務不可用,系統會自動呼叫fallbackMethod方法。如果被調服務正常的話,則與前一節的處理方式一致。
我們接下來需要適當改造一下Controller,使其呼叫我們新寫的Service元件:
@RestController
public class ProductConsumerController {
@Autowired
ProductService productService;
@RequestMapping(value="/product-consumer", method=RequestMethod.GET)
public String callServiceExample() {
return productService.callPrudctService();
}
}
第3、4行:通過註解方式從Spring框架獲取服務元件;
第8行:通過呼叫我們新定義的服務元件,實現對遠端微服務的呼叫。
經過上述程式,當遠端微服務不可用時,會顯示錯誤資訊,如果遠端微服務可用,則返回正常的呼叫結果。