续:

Hystrix介绍

Hystrix是如何工作的

SpringCloud学习笔记(3)——Hystrix

Hystrix使用

 package com.cjs.example;

 import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey; public class CommandHelloWorld extends HystrixCommand<String> { private String name; public CommandHelloWorld(HystrixCommandGroupKey group, String name) {
super(group);
this.name = name;
} public CommandHelloWorld(Setter setter, String name) {
super(setter);
this.name = name;
} @Override
protected String run() throws Exception {
if ("Alice".equals(name)) {
throw new RuntimeException("出错了");
}
return "Hello, " + name;
} @Override
protected String getFallback() {
return "Failure, " + name;
} }
 package com.cjs.example;

 import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import org.junit.Test;
import rx.Observable;
import rx.Observer; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals; public class CommandHelloWorldTest { @Test
public void testSync() {
HystrixCommandGroupKey hystrixCommandGroupKey = HystrixCommandGroupKey.Factory.asKey("ExampleGroup");
CommandHelloWorld command = new CommandHelloWorld(hystrixCommandGroupKey, "World");
String result = command.execute();
assertEquals("Hello, World", result);
} @Test
public void testAsync() throws ExecutionException, InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ExampleGroup");
assertEquals("Hello, Jack", new CommandHelloWorld(groupKey, "Jack").queue().get());
assertEquals("Hello, Rose", new CommandHelloWorld(groupKey, "Rose").queue().get()); CommandHelloWorld command = new CommandHelloWorld(groupKey, "Cheng");
Future<String> future = command.queue();
String result = future.get();
assertEquals("Hello, Cheng", result); // blocking
Observable<String> observable = new CommandHelloWorld(groupKey, "Lucy").observe();
assertEquals("Hello, Lucy", observable.toBlocking().single()); // non-blocking
Observable<String> observable2 = new CommandHelloWorld(groupKey, "Jerry").observe();
observable2.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("completed");
} @Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
} @Override
public void onNext(String s) {
System.out.println("onNext: " + s);
}
});
} @Test
public void testFail() throws ExecutionException, InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Group2");
assertEquals("Failure, Alice", new CommandHelloWorld(groupKey,"Alice").execute());
assertEquals("Failure, Alice", new CommandHelloWorld(groupKey,"Alice").queue().get());
} @Test
public void testProp() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Group3"); HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter()
.withCoreSize(10)
.withMaximumSize(10); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(true)
.withExecutionTimeoutInMilliseconds(100); HystrixCommand.Setter setter = HystrixCommand.Setter.withGroupKey(groupKey);
setter.andThreadPoolPropertiesDefaults(threadPoolProperties);
setter.andCommandPropertiesDefaults(commandProperties); assertEquals("Hello, Cheng", new CommandHelloWorld(setter, "Cheng").execute()); }
}

Spring Boot中使用Hystrix

1. Maven依赖

2. 使用@HystrixCommand注解

 package com.cjs.example;

 import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/greet")
public class GreetController { @HystrixCommand(fallbackMethod = "onError",
commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2")},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "5"),
@HystrixProperty(name = "maximumSize", value = "5"),
@HystrixProperty(name = "maxQueueSize", value = "10")
})
@RequestMapping("/sayHello")
public String sayHello(String name) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, " + name;
} @HystrixCommand
@RequestMapping("/sayHi")
public String sayHi(String name) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("name不能为空");
}
return "Good morning, " + name;
} /**
* 如果fallback方法的参数和原方法参数个数不一致,则会出现FallbackDefinitionException: fallback method wasn't found
*/
public String onError(String name) {
return "Error!!!" + name;
} }

3. Hystrix配置

 package com.cjs.example;

 import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.servlet.Servlet; @Configuration
public class HystrixConfig { /**
* A {@link ServletContextInitializer} to register {@link Servlet}s in a Servlet 3.0+ container.
*/
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
return new ServletRegistrationBean(new HystrixMetricsStreamServlet(), "/hystrix.stream");
} /**
* AspectJ aspect to process methods which annotated with {@link HystrixCommand} annotation.
*
* {@link HystrixCommand} annotation used to specify some methods which should be processes as hystrix commands.
*/
@Bean
public HystrixCommandAspect hystrixCommandAspect() {
return new HystrixCommandAspect();
} }

4. hystrix-dashboard

http://localhost:7979/hystrix-dashboard/

参考

https://github.com/Netflix/Hystrix/wiki/Configuration

https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-metrics-event-stream

https://github.com/Netflix-Skunkworks/hystrix-dashboard

Spring Boot 集成 Hystrix的更多相关文章

  1. Spring Boot集成Jasypt安全框架

    Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPl ...

  2. Spring boot集成swagger2

    一.Swagger2是什么? Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格 ...

  3. Spring Boot 集成 Swagger,生成接口文档就这么简单!

    之前的文章介绍了<推荐一款接口 API 设计神器!>,今天栈长给大家介绍下如何与优秀的 Spring Boot 框架进行集成,简直不能太简单. 你所需具备的基础 告诉你,Spring Bo ...

  4. spring boot 集成 zookeeper 搭建微服务架构

    PRC原理 RPC 远程过程调用(Remote Procedure Call) 一般用来实现部署在不同机器上的系统之间的方法调用,使得程序能够像访问本地系统资源一样,通过网络传输去访问远程系统资源,R ...

  5. Spring Boot 集成Swagger

    Spring Boot 集成Swagger - 小单的博客专栏 - CSDN博客https://blog.csdn.net/catoop/article/details/50668896 Spring ...

  6. spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,guava限流,定时任务案例, 发邮件

    本文介绍spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,定时任务案例 集成swagger--对于做前后端分离的项目,后端只需要提供接口访问,swagger提供了接口 ...

  7. Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

    上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...

  8. (转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS

    http://www.ityouknow.com/springboot/2018/01/16/spring-boot-fastdfs.html 上篇文章介绍了如何使用 Spring Boot 上传文件 ...

  9. Spring Boot集成JPA的Column注解命名字段无效的问题

    偶然发现,Spring Boot集成jpa编写实体类的时候,默认使用的命名策略是下划线分隔的字段命名. Spring Boot版本:1.5.4.release 数据表: id int, userNam ...

随机推荐

  1. 027 storm面试小题

    1.大纲 Storm工作原理是什么? 流的模式是什么?默认是什么? 对于mapreduce如何理解? Storm的特点和特性是什么? Storm组件有哪些? 2.Storm工作原理是什么? 相对于ha ...

  2. tomcat指定运行jdk

    set JAVA_HOME=D:\Program Files\Java\jdk7\jdk1.7.0_51 set JRE_HOME=D:\Program Files\Java\jdk7\jre7路径根 ...

  3. SpringBoot简单入门

    一.创建SpringBoot项目 1.创建maven项目,pom引入springboot父级启动器(starter)依赖: <?xml version="1.0" encod ...

  4. 第三方npm包安装失败

    最近升级一些第三方库,老是出现无法正常安装npm的现象. 一.问题现象 1.webpack4安装失败 // 报错信息 webpack Maximum call stack size exceeded ...

  5. AutoCAD下载

    AutoCAD 2019 64位破解版 附注册机和安装教程  1.71G AutoCAD 2019 64位精简优化版 珊瑚の海简体中文版691.08M

  6. MyBatis3系列__06查询的几点补充

    关于查询的一点补充: 当查询部门信息时,希望查询该部门下的所有员工,下面会采取两种方式实现: 1.联合查询 public Department getDeptWithEmpById(Integer i ...

  7. Python3系列__01Python安装

    Python和Java一样是跨平台的,它可以运行在Windows.Mac和各种Linux/Unix系统上.所以你在一个平台上面上写的代码在另一个平台仍能正常运行. 要学习Python编程,你需要做的就 ...

  8. BZOJ 3864

    dp of dp 我就是来贴个代码 #include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=(a ...

  9. Tomcat手动部署Web项目详细步骤

    阅读须知:文章基于Tomcat8,其它版本若有差异,请自行辨别.本文为博主原创文章,转载请附原文链接. 不借助任何IDE,这里介绍在Tomcat中手动部署web项目的三种方式: 1.部署解包的weba ...

  10. VUE 一些环境配置

    1. 安装  nrm 一键切换npm源 npm i nrm -g       [安装命令工具] nrm ls                 [罗列出所有的源] nrm use taobao  [使用 ...