版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/88379530
本文是本人学习Hystrix
总结的第一篇,经典的Hello World
应用。本应用特征如下 :
- 纯
java
项目 ;- 暂不涉及结合
Spring
使用,以便专注于Hystrix
自身;
- 暂不涉及结合
- 使用
junit
观察运行效果 ; - 使用
maven
管理依赖;
1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>tut.zero</groupId>
<artifactId>hystrix</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.18</version>
</dependency>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 定义Hello World
Hystrix Command
package tut.zero.simple;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
/**
* 一个简单的 HystrixCommand 实现,执行结果为 String 类型
*/
public class CommandHelloWorld extends HystrixCommand<String> {
private String name;
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
return "Hello " + name + "!";
}
}
3. 测试运行定义的Hystrix Command
package tut.zero;
import tut.zero.middle.MockRemoteService;
import tut.zero.middle.MockRemoteServiceCommand;
import tut.zero.simple.CommandHelloWorld;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Test;
import java.util.concurrent.Future;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class HystrixTest {
/**
* 一个简单的 HystrixCommand 的实现 和 调用演示
*/
@Test
public void testCommandHelloWorld() throws Exception{
{// 同步方式调用 HystrixCommand
String result = new CommandHelloWorld("World").execute();
assertThat(result, equalTo("Hello World!"));
}
{// 异步方式调用 HystrixCommand
Future<String> result = new CommandHelloWorld("WORLD").queue();
assertThat(result.get(), equalTo("Hello WORLD!"));
}
}
}
该测试执行应该能够正常通过,并且演示了使用HystrixCommand
的基本方法 :
- 同步调用
T execute()
(这里T是结果数据类型) - 异步调用
Future<T> queue()
(这里T是结果数据类型)