本文節選自《瘋狂Spring Cloud微服務架構實戰》
京東購買地址::https://item.jd.com/12256011.html
噹噹網購買地址::http://product.dangdang.com/25201393.html
Spring Cloud教學視頻:http://blog.csdn.net/boxiong86/article/details/78399104
Spring Cloud電子書:http://blog.csdn.net/boxiong86/article/details/78488226
19 Spring Cloud中使用Hystrix
Hystrix主要用於保護調用服務的一方,如果被調用的服務發生故障,符合一定條件,就開啓斷路器,對調用的程序進行隔離。在開始講述本章的內容前,先準備測試項目,本章例子所使用的項目如下:
spring-hystrix-server:Eureka服務器,端口爲8761,代碼目錄codes\06\6.4\spring-hystrix-server。
spring-hystrix-provider:服務提供者,本例只需要啓動一個實例,端口爲8080,默認提供“/person/{personId}”服務,根據personId參數返回一個Person實例,另外再提供一個“/hello”服務,返回普通的字符串。代碼目錄爲codes\06\6.4\spring-hystrix-provider。
spring-hystrix-invoker:服務調用者,9000端口,代碼目錄codes\06\6.4\spring-hystrix-invoker。
整合Hystrix
爲服務調用者(spring-hystrix-invoker)項目添加依賴,添加後的依賴如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
在服務調用者的應用啓動類中,加入啓用斷路器的註解,請見以下代碼片斷:
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class InvokerApplication {
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(InvokerApplication.class, args);
}
}
新建服務類,在服務方法中調用服務,請見代碼清單6-17。
代碼清單6-17:
codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\PersonService.java
@Component
public class PersonService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "getPersonFallback")
public Person getPerson(Integer id) {
//使用RestTemplate調用Eureka服務
Person p = restTemplate.getForObject(
"http://spring-hystrix-provider/person/{personId}",
Person.class, id);
return p;
}
/**
*回退方法,返回一個默認的Person
*/
public Person getPersonFallback(Integer id) {
Person p = new Person();
p.setId(0);
p.setName("Crazyit");
p.setAge(-1);
p.setMessage("request error");
return p;
}
}
服務類中注入了RestTemplate,服務方法使用了@HystrixCommand註解進行修飾,並且配置了回退方法。@HystrixCommand註解由Hystrix的“javanica”項目提供,該項目主要是爲了簡化Hystrix的使用。被@HystrixCommand修飾的方法,Hystrix(javanica)會使用AspectJ對其進行代理,Spring會將相關的類轉換爲Bean放到容器中,在Spring Cloud中,我們無需過多關心Hystrix的命令管理。
接下來,編寫控制器,調用服務類的方法,請見代碼清單6-18。
代碼清單6-18:
codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\InvokerController.java
@RestController
@Configuration
public class InvokerController {
@Autowired
private PersonService personService;
@RequestMapping(value = "/router/{personId}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public Person router(@PathVariable Integer personId) {
Person p = personService.getPerson(personId);
return p;
}
}
控制器實現較爲簡單,直接注入PersonService,調用方法即可,按以下步驟啓動集羣:
啓動“spring-hystrix-server”,本例中配置端口爲8761。
啓動“spring-hystrix-provider”,啓動一個實例,端口爲8080。
啓動“spring-hystrix-invoker”,端口爲9000。
打開瀏覽器訪問:http://localhost:9000/router/1,輸出如下:
{"id":1,"name":"Crazyit","age":33,"message":"http://localhost:8080/person/1"}
停止服務提供者(spring-hystrix-provide),即停止8080端口,再訪問9000端口的地址,輸出如下:
{"id":0,"name":"Crazyit","age":-1,"message":"request error"}
根據輸出可知,由於調用失敗,觸發了回退方法。
命令配置
Spring Cloud中使用@HystrixCommand來聲明一個命令,命令的相關配置,也可以在該註解中進行,以下的代碼片斷,配置了幾個屬性:
/**
*測試配置,對3個key進行命名
*設置命令執行超時時間爲1000毫秒
*設置命令執行的線程池大小爲1
*/
@HystrixCommand(
fallbackMethod="testConfigFallback", groupKey="MyGroup",
commandKey="MyCommandKey", threadPoolKey="MyCommandPool",
commandProperties={
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
value = "1000")
},
threadPoolProperties={
@HystrixProperty(name = "coreSize",
value = "1")
})
除了以上的幾個配置外,@HystrixCommand註解還可以使用ignoreExceptions來處理異常的傳播,請見以下代碼片斷:
/**
*聲明瞭忽略MyException,如果方法拋出MyException,則不會觸發回退
*/
@HystrixCommand(ignoreExceptions = {MyException.class},
fallbackMethod="testExceptionFallBack")
public String testException() {
throw new MyException();
}
Hystrix的命令、線程配置較多,由於篇幅所限,本小節僅簡單地列舉幾個,讀者可舉一反三,按需要進行配置。
默認配置
對於一些默認的配置,例如命令組的key等,可以使用@DefaultProperties註解,這樣就減少了@HystrixCommand註解的代碼量。以下代碼片斷展示如何使用@DefaultProperties:
@DefaultProperties(groupKey="GroupPersonKey")
public class PersonService {
@HystrixCommand // group key將使用“GroupPersonKey”
public String hello() {
return "";
}
}
除了定義GroupKey外,還支持@HystrixCommand的其餘配置,例如線程屬性、命令屬性等。
本文節選自《瘋狂Spring Cloud微服務架構實戰》
Spring Cloud教學視頻:http://blog.csdn.net/boxiong86/article/details/78399104
Spring Cloud電子書:http://blog.csdn.net/boxiong86/article/details/78488226