续:

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. 2018-2019-2 网络对抗技术 20162329 Exp2 后门原理与实践

    目录 1.实践基础 1.1.什么是后门 1.2.基础问题 2.实践内容 2.1.使用netcat获取主机操作Shell,cron启动 2.2.使用socat获取主机操作Shell, 任务计划启动 2. ...

  2. Linux中安装MySQL

    因为使用yum安装.安装过程需保证网络通畅 一.安装mysql 1.yum安装mysqlCentOS7默认数据库是mariadb,配置等用着不习惯,因此决定改成mysql,但是CentOS7的yum源 ...

  3. ABAQUS/CAE——Context

    Part(部分) 用户在Part单元内生成单个部件,可以直接在ABAQUS/CAE环境下用图形工具生成部件的几何形状,也可以从其他的图形软件输入部件.详细可参考ABAQUS/CAE用户手册第15章. ...

  4. es6的基本数据详解

    一.Set 基本用法:   1)ES6提供了新的数据机构-Set. 它类似于数组,但是成员的值都是唯一的,没有重复的值.Set本身是一个构造函数,用来生成Set数据结构. 先来看一段最简单的代码: 1 ...

  5. 使用Ant Design的select组件时placeholder不生效/不起作用的解决办法

    先来说说使用Ant Design和Element-ui的感觉吧. 公司的项目开发中用的是vue+element-ui,使用了一通下来后,觉得element-ui虽然也有一些问题或坑,但这些小问题或坑凭 ...

  6. kvm+libvirt虚拟机快照浅析[转]

    浅析snapshots, blockcommit,blockpull 作者:Kashyap Chamarthy <kchamart#redhat.com> Date: Tue, 23 Oc ...

  7. scrapy的基本语法

    1.创建爬虫: scrapy genspider爬虫名 域名 注意:爬虫的名字不能和项目名相同 2. scrapy list    --展示爬虫应用列表 scrapy crawl爬虫应用名称      ...

  8. python 模型 ORM简介

    Django之ORM (Object Relational Mapping(ORM)一.ORM介绍1.ORM概念 对象关系映射模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术.2.OR ...

  9. request.getRequestDispatcher跳转jsp页面失败

    我在JS里面写了个Ajax,传值给控制器,然后利用request.getRequestDispatcher(),打算跳转至另外一个页面.但是没有跳转成功,运行之后没反应. 在网上搜了资料发现,利用aj ...

  10. ubuntu 修改系统时间无效

    用root用户修改服务器时间无效:使用hwclock -w也不行 解决方法: 需要取消自动从互联网同步时间才可以的 timedatectl set-ntp 0 上面的命令可以关闭自动同步,然后你再设置 ...