Hystrix能做什么?
1. 延時(shí)和容錯(cuò):防止級(jí)聯(lián)失敗/服務(wù)優(yōu)雅降級(jí)/快速失敗,快速恢復(fù)/斷路由/超時(shí)處理
2. 實(shí)時(shí)操作
3. 并發(fā)操作
Hystrix在微服務(wù)架構(gòu)中扮演著斷路由這一重要的角色,而我們項(xiàng)目中主要看中如上第1條作用,通過Command模式,提供如上服務(wù)。
Github: https://github.com/Netflix/Hystrix
Maven配置
hystrix核心配置
groupId=com.netflix.hystrix
artifactId=hystrix-core
version=1.5.10
hystrix注解配置
groupId=com.netflix.hystrix
artifactId=hystrix-javanica
version=1.5.10
ApplicationContext.xml配置
通過Spring AOP機(jī)制實(shí)現(xiàn)注解級(jí)配置范咨。
<aop:aspectj-autoproxy />
<bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect" />
服務(wù)組件實(shí)現(xiàn)
通過HystrixCommand注解指定目標(biāo)方法接受Hystrix管理
通過fallbackMethod指定方法失敗時(shí)執(zhí)行的替代邏輯,也可以認(rèn)為是降級(jí)邏輯
可以看到厂庇,本例故意讓sayHello方法拋出Runtime異常渠啊,實(shí)際情況可能是遠(yuǎn)程服務(wù)調(diào)用調(diào)用超時(shí),或者方法執(zhí)行異常等等
```
package com.legend.springmvc.quickstart.hystrix;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Component;
/**
* Created by allen on 05/04/2017.
*/
@Component
public class HelloWorld2Command {
@HystrixCommand(fallbackMethod = "fallback")
public String sayHello(String name) {
// return "Hello2 " + name + "!";
throw new RuntimeException("Failed");
}
public String fallback(String name) {
return "Graceful fallback " + name + "!";
}
}
```
客戶端應(yīng)用
Spring自動(dòng)注入管理
```
package com.legend.springmvc.quickstart.impl;
import com.legend.springmvc.quickstart.HelloWorldService;
import com.legend.springmvc.quickstart.JdbcProperties;
import com.legend.springmvc.quickstart.hystrix.HelloWorld2Command;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by allen on 7/25/16.
*/
@Controller
public class HelloWorldServiceImpl implements HelloWorldService {
@Autowired
private JdbcProperties jdbcProperties;
@Autowired HelloWorld2Command helloWorld2Command;
@RequestMapping(value = "/hello/{msg}")
@ResponseBody
public String hello(@PathVariable(value = "msg") String paramHello) {
String result = helloWorld2Command.sayHello("Bob");
return "Hello World " + paramHello + "; driver=" + jdbcProperties.getDriver()
+ "; url=" + jdbcProperties.getUrl() + "; username=" + jdbcProperties.getUsername()
+ "; password=" + jdbcProperties.getPassword() + "; result=" + result;
}
}
```
結(jié)果輸出
http://localhost:8080/springmvc/hello/allen
Hello World allen; driver=oracle.jdbc.driver.OracleDriver; url=jdbc:oracle:thin:@127.0.0.1:1521:XE; username=test; password=test; result=Graceful fallback Bob!
源碼參考:https://github.com/AllenLiuGit/springmvc-quickstart.git
HelloWorld2Command.java/HelloWorldServiceImpl.java/applicationContext-servlet.xml/web.xml