Spring Boot 集成 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的更多相关文章
- Spring Boot集成Jasypt安全框架
Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPl ...
- Spring boot集成swagger2
一.Swagger2是什么? Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格 ...
- Spring Boot 集成 Swagger,生成接口文档就这么简单!
之前的文章介绍了<推荐一款接口 API 设计神器!>,今天栈长给大家介绍下如何与优秀的 Spring Boot 框架进行集成,简直不能太简单. 你所需具备的基础 告诉你,Spring Bo ...
- spring boot 集成 zookeeper 搭建微服务架构
PRC原理 RPC 远程过程调用(Remote Procedure Call) 一般用来实现部署在不同机器上的系统之间的方法调用,使得程序能够像访问本地系统资源一样,通过网络传输去访问远程系统资源,R ...
- Spring Boot 集成Swagger
Spring Boot 集成Swagger - 小单的博客专栏 - CSDN博客https://blog.csdn.net/catoop/article/details/50668896 Spring ...
- spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,guava限流,定时任务案例, 发邮件
本文介绍spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,定时任务案例 集成swagger--对于做前后端分离的项目,后端只需要提供接口访问,swagger提供了接口 ...
- Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件
上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...
- (转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS
http://www.ityouknow.com/springboot/2018/01/16/spring-boot-fastdfs.html 上篇文章介绍了如何使用 Spring Boot 上传文件 ...
- Spring Boot集成JPA的Column注解命名字段无效的问题
偶然发现,Spring Boot集成jpa编写实体类的时候,默认使用的命名策略是下划线分隔的字段命名. Spring Boot版本:1.5.4.release 数据表: id int, userNam ...
随机推荐
- 2018-2019-3 网络对抗技术 20165235 Exp3 免杀原理与实践
2018-2019-3 网络对抗技术 20165235 Exp3 免杀原理与实践 基础问题回答 杀软是如何检测出恶意代码的? 1.对某个文件的特征码进行分析,(特征码就是一类恶意文件中经常出现的一段代 ...
- SpringBoot配置文件
一.配置文件 配置文件应该是无论在哪个框架中都是一个重要角色,而我们最为常用的xxx.xml和xxx.properties,还有springboot推荐使用的xxx.yml. 二.SpringBoot ...
- SpringCloud Gateway 测试问题解决
本文针对于测试环境SpringCloud Gateway问题解决. 1.背景介绍 本文遇到的问题都是在测试环境真正遇到的问题,不一定试用于所有人,仅做一次记录,便于遇到同样问题的干掉这些问题. 使用版 ...
- 使用GitHub作为Maven仓库并引用
网上太多的博客都是那些傻逼抄袭,然后直接复制粘贴然后就成为自己的博客了,这种人,真的很欠揍,我在网上查了一个下午的资料,终于找到一个写得非常详细的兄弟 链接如下:https://blog.csdn.n ...
- 大数加法~HDU 1002 A + B Problem II
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1002 题意: 数学题,A+B; 思路,这个数非常大,普通加法一定会超时,所以用大数加法.大数加法的基 ...
- sqlalchemy 使用
创建连接 # 参数: '数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名' from sqlalchemy import create_engine engine = crea ...
- vty密码登录,到AAA验证登录,以及远程配置网络
华为的的最简易的远程登录方式,就是密码登录了. 配置命令如下图: 最重要的是权限: 访问级(0级).监控级(1级).系统级(2级)和管理级(3级) 在以上基础上,做了一个远程配置方式,通过一台,修改其 ...
- Android Gradle Task
Tasks runnable from root project ------------------------------------------------------------ Androi ...
- pyhton 监听文件输入实例
def tail(filename): f = open(filename,encoding='utf-8') while True: line = f.readline() if line.stri ...
- Notepad++常用快捷键
Ctrl-H 打开Find / Replace 对话框 Ctrl-D 复制当前行 Ctrl-L 删除当前行 Ctrl-T 上下行交换 F3 找下一个 Shift-F3 ...