续:

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. pdfjs预览pdf文件的两种方式(可复制)

    1.以图片形式进行展示: version:采用1.x版本,2.0版本会有字体显示不完整的问题:参考 这里使用1.8.170 <script th:src="@{/pdfjs/build ...

  2. vue基础4-数据绑定

    1.v-bind 只能实现数据额单向绑定,从M到V,无法实现数据的双向绑定 改变页面输入框的值,打印数据并未改变. 2.v-model 可以实现数据的双向绑定,从M到V.V到M.  注意:v-mode ...

  3. 20165220《网络对抗技术》week1 Exp0 Kali安装

    下载地址: 地址:https://www.kali.org/downloads/ 安装: 登录 配置网络: 共享文件夹设置: 安装软件: 输入apt-get install ibus ibus-pin ...

  4. Web 性能优化:21 种优化 CSS 和加快网站速度的方法

    这是 Web 性能优化的第 4 篇,上一篇在下面看点击查看: Web 性能优化:使用 Webpack 分离数据的正确方法 Web 性能优化:图片优化让网站大小减少 62% Web 性能优化:缓存 Re ...

  5. Win10 Store 还原

    Get-AppxPackage -allusers | Select Name, PackageFullName Add-appxpackage -register "C:\Program ...

  6. yum程序下载被占用

    Loaded plugins: fastestmirror, refresh-packagekit, security Existing lock /var/run/yum.pid: another ...

  7. 输出九九乘法表(Python、Java、C、C++、JavaScript)

    最近在学python的过程中,接触到了循环的知识,以及这个案例,于是写了下!感觉还不错,然后就用其它几种语言也试了下!! 接下来,就跟大家分享下实现方法!! 实现输出九九乘法表,主要用到的是循环的知识 ...

  8. NOIP2008 立体图

    题目描述 小渊是个聪明的孩子,他经常会给周围的小朋友们将写自己认为有趣的内容.最近,他准备给小朋友们讲解立体图,请你帮他画出立体图. 小渊有一块面积为m*n的矩形区域,上面有m*n个边长为1的格子,每 ...

  9. 开发中少不了的Fun -- 微信开发IOS端alert/confirm提示信息,去除网址(URL)的方法

    在微信公众号开发的时候在使用[alert/confirm]弹出提示或者警告信息的时候,[alert/confirm]会将该公众号的网址显示出来,这样很不美观.所以很多时候我们会选择去除那个网址提示内容 ...

  10. c# Winform Invoke 的用法

    在Winform中线程更新UI线程 例如:Form中有一个DataGridView,我们使用Thread查询后,更新这个表格,如果在Thread中直接更新会报错. Thread th = new Th ...