Hystrix能做什么?
1. 延时和容错:防止级联失败/服务优雅降级/快速失败,快速恢复/断路由/超时处理
2. 实时操作
3. 并发操作
Hystrix在微服务架构中扮演着断路由这一重要的角色,而我们项目中主要看中如上第1条作用,通过Command模式,提供如上服务。
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机制实现注解级配置。
<aop:aspectj-autoproxy />
<bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect" />
服务组件实现
通过HystrixCommand注解指定目标方法接受Hystrix管理
通过fallbackMethod指定方法失败时执行的替代逻辑,也可以认为是降级逻辑
可以看到,本例故意让sayHello方法抛出Runtime异常,实际情况可能是远程服务调用调用超时,或者方法执行异常等等
```
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 + "!";
}
}
```
客户端应用
Spring自动注入管理
```
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;
}
}
```
结果输出
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