1.导入jar包
<dependencies> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> </dependencies>
2.编写hystrix测试类
(1)正常情况
import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HelloCommand extends HystrixCommand<String> { protected HelloCommand() { super(HystrixCommandGroupKey.Factory.asKey("TestGroup")); } @Override protected String run() throws Exception { String url = "http://localhost:8080/test/hello"; HttpGet httpGet = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse response = httpClient.execute(httpGet); String result = EntityUtils.toString(response.getEntity()); return result; } }
(2)异常情况
import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HelloErrorCommand extends HystrixCommand<String> { protected HelloErrorCommand() { super(HystrixCommandGroupKey.Factory.asKey("TestGroup")); } @Override protected String run() throws Exception { String url = "http://localhost:8080/test/erroHello"; HttpGet httpGet = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse response = httpClient.execute(httpGet); String result = EntityUtils.toString(response.getEntity()); return result; } @Override protected String getFallback() { System.out.println("这是回退方法"); return "回退方法"; } }
(3)测试方法
public class HelloMain { public static void main(String[] args) { HelloCommand command = new HelloCommand(); String result = command.execute(); System.out.println(result); HelloErrorCommand command1 = new HelloErrorCommand(); String result1 = command1.execute(); System.out.println(result1); } }
3.服务接口
@GetMapping(value = "/hello") public String hello() { return "hello world"; } @GetMapping(value = "/erroHello") public String erroHello() throws Exception{ Thread.sleep(10000); return "hello error"; }