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. postman接口自动化测试之如何使用)

    postman 是一款强大网页调试工具的客户端,postman为用户提供强大的 Web API & HTTP 请求调试功能.postman能够发送任何类型的HTTP 请求 (GET, HEAD ...

  2. python之requests模块中的params和data的区别

    params的时候之间接把参数加到url后面,只在get请求时使用: import requests url='https://api.ireaderm.net/account/charge/info ...

  3. linux运维、架构之路-ansible批量管理

    一.ansible软件 1.介绍 ①ansible是一个基于Python开发的自动化运维工具 ②其功能实现基于SSH远程连接服务 ③ansible可以实现批量系统配置.批量软件部署.批量文件拷贝.批量 ...

  4. [转]Html.DropDownList()的用法 ( Asp.Net MVC)

    Html.DropDownList()赋默认值: 页面代码如下: <% List<SelectListItem> list = new List<SelectListItem& ...

  5. 【HDOJ6616】Divide the Stones(构造)

    题意:给定n堆石子,第i堆的个数为i,要求构造出一种方案将其分成k堆,使得这k堆每堆数量之和相等且堆数相等 保证k是n的一个约数 n<=1e5 思路:先把非法的情况判掉 n/k为偶数的方法及其简 ...

  6. [CSP-S模拟测试]:棋盘(数学+高精度)

    题目描述 在一个大小为$N\times N$的棋盘上,放置了$N$个黑色的棋子.并且,对于棋盘的每一行和每一列,有且只有一个棋子.现在,你的任务是再往棋盘上放置$N$个白色的棋子.显然,白色棋子不能与 ...

  7. eureka注册中心wro.css wro.js 404

    注册中心和配置中心放在一个module里面,如果不配置配种中心的访问前缀,会被config拦截.所以改动如下: package com.cloud.stagging.lhcloudeureka; im ...

  8. JS-生成器函数(function 星号)的暂停和恢复(yield)

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/function* https://devel ...

  9. 测开之路七十二:性能测试工具之locust简介

    locust官网:https://locust.io/ locust安装(不支持python3.7):pip install locustio   或者pycharm安装 官网给出的样例 根据官网代码 ...

  10. File类的相关方法

    java.io.File类 文件和路径名的抽象表达形式 java把电脑中的文件和文件夹(目录)封装了一个File类,我们可以使用File类对文件和文件夹进行如下操作 创建一个文件/文件夹 删除 获取 ...