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. Python---编辑器安装和print函数

    Python---编辑器安装和print函数 -------------------------------------------------------- 一.Python是什么? Python是 ...

  2. GPS通讯 数据包解析

    全球时区的划分: 每个时区跨15°经度.以0°经线为界向东向西各划出7.5°经度,作为0时区.即0时区的经度范围是7.5°W——7.5°E.从7.5°E与7.5°W分别向东.向西每15°经度划分为一个 ...

  3. SSM项目web.xml等配置文件中如何查找类的全路径名?

    如题, web.xml,applicationContext.xml 等配置文件中,有时不会出现自动提示类的名字,这时如何查找类的全路径名,如下图所示: 1.鼠标右键单击菜单栏Navigate选项,选 ...

  4. php array_splice()函数 语法

    php array_splice()函数 语法 作用:从数组中移除选定的元素,并用新元素取代它.dd马达价格 语法:array_splice(array,start,length,array) 参数: ...

  5. 【CF1255A】Changing Volume【思维】

    题意:每次可以-5/-2/-1/+1/+2/+5,问是否存在方案使得A变成B 题解:首先我们可以设A<B,若A>B,则交换AB,因为A到B和B到A是互逆的过程,所以可以交换 其次将B-=A ...

  6. shp文件导入数据库

    数据库服务器(引擎) sql server oracle nosql sql语句... 从数据库端导入:新建数据库,导入shp文件 发布地图服务 jdbc.sdk

  7. CTF_工具网址收藏

    杂项 条形码在线扫描 :    https://online-barcode-reader.inliteresearch.com/ PS弄反色ctr+i    :  https://zhidao.ba ...

  8. field.getModifiers() 返回值

    field.getModifiers() 返回值 public static final  的值是 25 private 的值是2  测试如下 Class clazz=MyModel.class; F ...

  9. CSS3中哪些新属性—阴影、文本省略(1)

    CSS3中的阴影,我知道的就是盒阴影和文字阴影.两者使用大同小异. 1.文字阴影 不知道为啥阴影会被开发出来,觉得这没啥好用啊.用了之后发现好像还行,使页面更有立体感了那么一点点.看起来趣味性强一点. ...

  10. 常用的Android关键词定位方法

    1字符串,特征字 根据程序运行中出现的特征字词进行搜索,从而获取定位到程序的相关位置之中.以前用 得比较多,不过现在一般难以找到想要的关键词.有时候需要对特征字进行拆分来进行搜索.才 能获得一点提示. ...