1.引入依赖

要排除hystrix-core里的archaius-core,否则报错

<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.</version>
<exclusions>
<exclusion>
<artifactId>archaius-core</artifactId>
<groupId>com.netflix.archaius</groupId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>com.netflix.archaius</groupId>
<artifactId>archaius-core</artifactId>
<version>0.7.</version>
</dependency> <dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>

2.定义HttpHystrixCommand类

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j; @Slf4j
public class HttpHystrixCommand extends HystrixCommand<ResponseEntity<String>> { private org.springframework.http.HttpMethod httpMethod;
private HttpEntity httpEntity;
private String url;
private RestTemplate restTemplate = new RestTemplate(); public HttpHystrixCommand(String url, HttpMethod httpMethod, HttpEntity<?> httpEntity) {
// 设置3秒超时
super(HystrixCommandGroupKey.Factory.asKey("http_hystrix_command_group_key"), );
this.httpMethod = httpMethod;
this.httpEntity = httpEntity;
this.url = url;
} public HttpHystrixCommand(String url, HttpEntity<?> httpEntity) {
this(url, HttpMethod.POST, httpEntity);
} public HttpHystrixCommand(String url) {
this(url, HttpMethod.GET, null);
} public ResponseEntity<String> post() {
this.httpMethod = HttpMethod.POST;
return execute();
} public ResponseEntity<String> get() {
this.httpMethod = HttpMethod.GET;
this.httpEntity = null;
return execute();
} @Override
protected ResponseEntity<String> run() throws Exception {
// Thread.sleep(3000);
return restTemplate.exchange(url, httpMethod, (HttpEntity) httpEntity, String.class);
} @Override
protected ResponseEntity<String> getFallback() {
Throwable executionException = getExecutionException();
if (executionException instanceof HystrixTimeoutException) {
log.error("请求因超时融断!url:{} param:{}", this.url, this.httpEntity, executionException);
} else if (executionException instanceof HystrixRuntimeException) {
log.error("请求直接融断!url:{} param:{}", this.url, this.httpEntity, executionException);
} else {
log.error("请求异常!url:{} param:{}", this.url, this.httpEntity, executionException);
} return new ResponseEntity<String>(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
}
}

3.测试

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springside.modules.utils.mapper.JsonMapper;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j; /**
*
*/ @Slf4j
public class HttpHystrixCommandTest {
public static void main(String[] args) {
ResponseEntity<String> response = new HttpHystrixCommand(
"https://aaa.xxx.com/setting/get?key=key1&source=h5")
.get();
if (response.getStatusCode().value() == org.springframework.http.HttpStatus.OK.value()) {
log.info("请求成功");
}else{
log.info("请求失败");
}
}
private static HttpHeaders defaultRequestHeaders = new HttpHeaders(); static {
defaultRequestHeaders.setContentType(MediaType.APPLICATION_JSON);
defaultRequestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
} public static HttpEntity<String> getHttpEntity(Object postData) {
return new HttpEntity<>(JsonMapper.INSTANCE.toJson(postData), defaultRequestHeaders);
} public static HttpEntity<String> getHttpEntity(String postData) {
return new HttpEntity<>(postData, defaultRequestHeaders);
}
}

4.正常的返回如下

INFO HttpHystrixCommandTest - 请求成功

5.异常(增加代码Thread.sleep(3000);)的返回如下:

ERROR HttpHystrixCommand - 请求因超时融断!url:https://aaa.xxx.com/setting/get?key=depository&source=h5 param:null
com.netflix.hystrix.exception.HystrixTimeoutException: null

使用HystrixCommand封装http请求的更多相关文章

  1. WebApi系列~基于单请求封装多请求的设计

    回到目录 怎么说,单请求封装多请求,这句话确实有点绕了,但还是要看清楚,想明白这到底是怎么一回事,单请求即一次请求(get,post,put,delete),封闭多请求,即在客户端发送的一个请求中可能 ...

  2. [iOS微博项目 - 3.3] - 封装网络请求

    github: https://github.com/hellovoidworld/HVWWeibo   A.封装网络请求 1.需求 为了避免代码冗余和对于AFN框架的多处使用导致耦合性太强,所以把网 ...

  3. 微信小程序初体验--封装http请求

    最近看了一下微信小程序,大致翻了一下,发现跟angular很相似的,但是比angular简单的很多具体可参考官方文档 https://mp.weixin.qq.com/debug/wxadoc/dev ...

  4. 结合prototype和xmlhttprequest封装ajax请求

    由于拖延症的严重以及年前准备年会(借口*^__^*) 导致这个小的的思考  现在才算完成 再怎么说也算是上班以来带我的前辈第一次这么正式的给我出题 不管是出于尊重还是自我要求我都决定把它简要的记下来 ...

  5. App 组件化/模块化之路——如何封装网络请求框架

    App 组件化/模块化之路——如何封装网络请求框架 在 App 开发中网络请求是每个开发者必备的开发库,也出现了许多优秀开源的网络请求库.例如 okhttp retrofit android-asyn ...

  6. 微信小程序教学第二章(含视频):小程序中级实战教程之预备篇 - 封装网络请求及 mock 数据

    § 封装网络请求及 mock 数据 本文配套视频地址: https://v.qq.com/x/page/i05544fogcm.html 开始前请把 ch2-3 分支中的 code/ 目录导入微信开发 ...

  7. 微信小程序之封装http请求

    下面将封装http请求服务部分的服务以及引用部分 // 本服务用于封装请求 // 返回的是一个promisepromise var sendRrquest = function (url, metho ...

  8. 微信小程序开发——使用promise封装异步请求

    前言: 有在学vue的网友问如何封装网络请求,这里以正在写的小程序为例,做一个小程序的请求封装. 关于小程序发起 HTTPS 网络请求的Api,详情可以参考官方文档:wx.request(Object ...

  9. React Native 网络请求封装:使用Promise封装fetch请求

    最近公司使用React作为前端框架,使用了异步请求访问,这里做下总结: React Native中虽然也内置了XMLHttpRequest 网络请求API(也就是俗称的ajax),但XMLHttpRe ...

随机推荐

  1. 修改图片尺寸网站https://www.yasuotu.com/

    修改图片尺寸网站https://www.yasuotu.com/

  2. php7 mysqli连接mysql的几种方式

    一.过程是方法 function connect(){ static $conn; if(!$conn){ $conn = mysqli_connect(DB_HOST,DB_USER,DB_PWD) ...

  3. 获取不到最新的url地址展示图片可以盖时间戳

    如:  $("#"+attachId).on('click', function() {                 params1 = [];                 ...

  4. Spring MVC (二)

    一.使用 @RequestMapping 映射请求 Spring MVC使用@RequestMapping注解为控制器指定可以处理哪些URL请求 在控制器的类定义以及方法定义处都可以标注 类定义处:提 ...

  5. phpexcel如何读和写大于26列的excel

    主要运用到PHPExcel_Cell类的两个方法 1读取excel大于26列时. PHPExcel_Cell::columnIndexFromString($highestColumm)://由列名转 ...

  6. 20180716-Java正则表达式

    import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{ public sta ...

  7. CF1182 D Complete Mirror——思路

    题目:http://codeforces.com/contest/1182/problem/D 很好的思路是从度数为1的点和直径来入手. 找一条直径.看看直径的两个端点是否合法. 如果都不合法,那么根 ...

  8. [CSP-S模拟测试]:Seat(概率DP+数学)

    题目描述 有$n+2$个座位等距地排成一排,从左到右编号为$0$至$n+1$.最开始时$0$号以及$n+1$号座位上已经坐了一个小$G$,接下来会有$n$个小$G$依次找一个空座位坐下.由于小$G$们 ...

  9. mysql中 key 、primary key 、unique key 和 index 有什么不同

    mysql中 key .primary key .unique key 和 index 有什么不同 key 是数据库的物理结构,它包含两层意义和作用, 一是约束(偏重于约束和规范数据库的结构完整性), ...

  10. Zsh vs. Bash不完全对比解析,zsh是一种更强大的被成为“终极”的Shell

    https://www.zhihu.com/question/21418449 Mort | Zsh vs. Bash:不完全对比解析(1) 2014-10-07  bdpqlxz     Zsh和B ...