1、添加依赖
Maven、Ivy、Gradle和其他工具的二进制文件和依赖信息可以在 http://search.maven.org
上找到。
Maven的例子:
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>x.y.z</version>
</dependency>
Ivy 的例子:
<dependency org="com.netflix.hystrix" name="hystrix-core" rev="x.y.z" />
如果你需要下载jar文件,而不是使用构建系统,创建一个Maven pom文件,如下所示:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.netflix.hystrix.download</groupId>
<artifactId>hystrix-download</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Simple POM to download hystrix-core and dependencies</name>
<url>http://github.com/Netflix/Hystrix</url>
<dependencies>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>x.y.z</version>
<scope/>
</dependency>
</dependencies>
</project>
然后排除:
mvn -f download-hystrix-pom.xml dependency:copy-dependencies
它将下载 hystrix-core-*.jar
及其依赖项到 ./target/dependency/
。
您需要 Java 6 或更高版本。
2、Hello World!
Hystrix 的最简单用法如下:
public class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
// a real example would do work like a network call here
return "Hello " + name + "!";
}
}
这个命令可以这样使用:
String s = new CommandHelloWorld("Bob").execute();
Future<String> s = new CommandHelloWorld("Bob").queue();
Observable<String> s = new CommandHelloWorld("Bob").observe();
更多的例子和信息可以在如何使用一节中找到。
示例源代码可以在 hystrix-examples 模块中找到。
3、项目构建
检出源代码并构建:
$ git clone git@github.com:Netflix/Hystrix.git
$ cd Hystrix/
$ ./gradlew build
简单的构建:
$ ./gradlew clean build
构建结果类似如下:
$ ./gradlew build
:hystrix-core:compileJava
:hystrix-core:processResources UP-TO-DATE
:hystrix-core:classes
:hystrix-core:jar
:hystrix-core:sourcesJar
:hystrix-core:signArchives SKIPPED
:hystrix-core:assemble
:hystrix-core:licenseMain UP-TO-DATE
:hystrix-core:licenseTest UP-TO-DATE
:hystrix-core:compileTestJava
:hystrix-core:processTestResources UP-TO-DATE
:hystrix-core:testClasses
:hystrix-core:test
:hystrix-core:check
:hystrix-core:build
:hystrix-examples:compileJava
:hystrix-examples:processResources UP-TO-DATE
:hystrix-examples:classes
:hystrix-examples:jar
:hystrix-examples:sourcesJar
:hystrix-examples:signArchives SKIPPED
:hystrix-examples:assemble
:hystrix-examples:licenseMain UP-TO-DATE
:hystrix-examples:licenseTest UP-TO-DATE
:hystrix-examples:compileTestJava
:hystrix-examples:processTestResources UP-TO-DATE
:hystrix-examples:testClasses
:hystrix-examples:test
:hystrix-examples:check
:hystrix-examples:build
BUILD SUCCESSFUL
Total time: 30.758 secs
在一个干净的构建中,你会看到单元测试运行,看起来像这样:
> Building > :hystrix-core:test > 147 tests completed