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 ...
随机推荐
- python-while else
count = 0 while count <= 5 : count += 1 if count == 3:break print("Loop",count) else: p ...
- STM8L052低功耗模式
Stm8L系列单片机的低功耗有五种模式: § wait模式 § Lowpower run模式 § Lowpower wait模式 § Active-haltwith full RTC模式 § Halt ...
- jQuery各类选择器
- 从Excel导数据到MySQL速度优化
运行环境: Windows10 和 Deepin15.7, MySQL14.4, Java1.8.0_181使用工具: poi,JDBC数据规模: 35万条,5个文件夹,146个Excel文件(.xl ...
- mac搭建简单的hls推流服务器遇到的问题(待更新)
实际操作步骤: 输入brew install nginx-full --with-rtmp-module命令出现以下报错: 需要先安装nginx服务器,运行命令brew tap homebrew/ng ...
- leetcode-求众数
题目:求众数 给定一个大小为 n 的数组,找到其中的众数.众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素. 你可以假设数组是非空的,并且给定的数组总是存在众数. 示例 1: 输入: [3,2,3 ...
- Kubernetes中的RBAC
Kubernetes中,授权有ABAC(基于属性的访问控制).RBAC(基于角色的访问控制).Webhook.Node.AlwaysDeny(一直拒绝)和AlwaysAllow(一直允许)这6种模式. ...
- linux mailbox模型
一.device tree中的写法 二. mailbox框架 (driver/mailbox/mailbox.c) struct mbox_controller { struct device *de ...
- kodexplorer免费网盘安装教程
KodExplorer是什么? KodExplorer可道云,原名芒果云,是基于Web技术的私有云和在线文件管理系统. 用户只需通过简单环境搭建,即可使用KodExplorer快速完成私有云/私有网盘 ...
- 面试题5-[剑指offer] 二维数组中的查找
题目 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. ...