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. BZOJ 1911 特别行动队 (斜率优化)

    $ BZOJ~1911~*~ $ 特别行动队: (斜率优化) $ solution: $ 感觉这道题目还是比较常规的,首先我们很容易想到DP,因为题目里面说了选出的人都是连续的,这意味着我们可以从前往 ...

  2. gulp自动化构建工具使用总结

    简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快的编写代码 ...

  3. man mkfs

    ---恢复内容开始--- MKFS(8)                                                                MKFS(8) NAME/名称  ...

  4. LeetCode--055--跳跃游戏(java)

    给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 判断你是否能够到达最后一个位置. 示例 1: 输入: [2,3,1,1,4] 输出: true ...

  5. C# 与 C++,语法差别有多小-第三章 C++数据类型 第一部分

    一,数据类型 C++: char  int short  long float double, unsigned long double(128位,19位有效数字), wchar_t, 浮点型文字常量 ...

  6. Python全栈开发,Day1

    一.Python介绍及版本 Python崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. 目前Python主要应用领域: 云计算:云计算最火的语言 WEB开发:众多优秀的WEB框架,众多大型网站均为 ...

  7. POJ 1797 Heavy Transprotation ( 最短路变形 || 最小生成树 )

    题意 : 找出 1 到 N 点的所有路径当中拥有最大承载量的一条路,输出这个最大承载量!而每一条路的最大承载量由拥有最大承载量的那一条边决定 分析 : 与 POJ 2253 相似且求的东西正好相反,属 ...

  8. C#在WinForm开发中Label换行方法

    很多朋友都会在开发WinForm中遇到Label要显示的内容太长,但却不能换行的问题.这里我总结了几种方法,供大家参考. 第一种是把Label的AutoSize属性设为False,手动修改Label的 ...

  9. hud 4347 The Closest M Points(KD-Tree)

    传送门 解题思路 \(KD-Tree\)模板题,\(KD-Tree\)解决的是多维问题,它是一个可以储存\(K\)维数据的二叉树,每一层都被一维所分割.它的插入删除复杂度为\(log^2 n\),它查 ...

  10. CF889 E Mod Mod Mod——DP

    题目:http://codeforces.com/contest/889/problem/E 这题真好玩. 官方题解说得很好. 想到相邻 a[ i ] 之间的段可能可以一起维护,但是不太会. 原来是表 ...