换一种口味实现 HttpClient

2024-03-23 11:32

本文主要是介绍换一种口味实现 HttpClient,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于注解 + 反射 + 动态代理

先上代码:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InvokerMethod {

enum HttpMethod {
Get, Post
}

HttpMethod method() default HttpMethod.Get;

String path() default "";

int timeout() default 5000;

}


public class HttpProxyFactoryBean implements FactoryBean {
private String interfaceName;
private InvocationHandler handler;
private Object proxy;
private Class<?> proxyType;

public void init() throws Exception {
Preconditions.checkNotNull(interfaceName);
Preconditions.checkNotNull(handler);

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
proxyType = ClassUtils.getClass(classLoader, interfaceName.trim());
proxy = Proxy.newProxyInstance(classLoader, new Class[] { proxyType }, handler);
}

@Override
public Object getObject() throws Exception {
return proxy;
}

@Override
public Class getObjectType() {
return proxyType;
}

@Override
public boolean isSingleton() {
return true;
}

public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}

public void setHandler(InvocationHandler handler) {
this.handler = handler;
}

}


public class HttpInvocationHandler implements InvocationHandler {

// 目标地址,如: http://www.example.com
private String host = "******";
// 申请的 key
private String key = "******";
// HttpClient
private CloseableHttpClient httpClient;

/**
* 初始化 HttpClient 。 HttpClient 的构造其实很有讲究的。
*/
public HttpInvocationHandler() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(1000)
.setSocketTimeout(1000)
.build();

PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 设置总的最大连接数
connectionManager.setMaxTotal(500);
// 设置单机最大连接数
connectionManager.setDefaultMaxPerRoute(100);
// 设置出口到目标地址的单机最大连接数
HttpHost httpHost = new HttpHost(parseHost()[1], 80);
connectionManager.setMaxPerRoute(new HttpRoute(httpHost), 100);

httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}

/**
* 代理方法,执行 http 请求。
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Preconditions.checkNotNull(httpClient);
Preconditions.checkNotNull(host);
Preconditions.checkNotNull(key);

HttpUriRequest httpRequest = buildHttpRequest(method, args);
if (httpRequest == null) {
throw new IllegalRequestException();
}

CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpRequest);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RemoteServiceException("Http status code: " + statusCode);
}
HttpEntity entity = httpResponse.getEntity();
Object response = null;
if (entity != null) {
InputStream inputStream = entity.getContent();
try {
response = JsonUtil.fromJson(new InputStreamReader(inputStream), method.getReturnType());
} finally {
inputStream.close();
}
}
return response;
} catch (Exception e) {
throw new RemoteServiceException(e);
} finally {
if (httpResponse != null) {
httpResponse.close();
httpRequest.abort();
}
}
}

/**
* 构造 Http 请求。
*/
private HttpUriRequest buildHttpRequest(Method method, Object[] args) {
InvokerMethod invokerMethod = method.getAnnotation(InvokerMethod.class);
if (invokerMethod == null) {
return null;
}
if (args == null || args.length == 0) {
return null;
}
Object request = args[0];
String jsonRequest = JsonUtil.toJson(request);
HttpUriRequest httpUriRequest;
switch (invokerMethod.method()) {
case Get:
httpUriRequest = createGetRequest(invokerMethod, jsonRequest);
break;
case Post:
httpUriRequest = createPostRequest(invokerMethod, jsonRequest);
break;
default:
httpUriRequest = null;
break;
}
return httpUriRequest;
}

/**
* 创建加密 Get 请求。
*/
private HttpUriRequest createGetRequest(InvokerMethod method, String jsonRequest) {
URI uri;
try {
String[] hostPair = parseHost();
uri = new URIBuilder()
.setScheme(hostPair[0])
.setHost(hostPair[1])
.setPath(method.path())
.addParameter("json", jsonRequest)
.addParameter("sign", encrypt(jsonRequest))
.addParameter("sign_type", "md5")
.build();
} catch (URISyntaxException e) {
return null;
}
RequestConfig config = RequestConfig.custom().setSocketTimeout(method.timeout()).build();
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(config);
return httpGet;
}

/**
* 创建加密 Post 请求。
*/
private HttpUriRequest createPostRequest(InvokerMethod method, String jsonRequest) {
URI uri;
try {
String[] hostPair = parseHost();
uri = new URIBuilder()
.setScheme(hostPair[0])
.setHost(hostPair[1])
.setPath(method.path())
.build();
} catch (URISyntaxException e) {
return null;
}
RequestConfig config = RequestConfig.custom().setSocketTimeout(method.timeout()).build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setConfig(config);
List<NameValuePair> pairs = Lists.newArrayListWithCapacity(3);
pairs.add(new BasicNameValuePair("json", jsonRequest));
pairs.add(new BasicNameValuePair("sign", encrypt(jsonRequest)));
pairs.add(new BasicNameValuePair("sign_type", "md5"));
httpPost.setEntity(new UrlEncodedFormEntity(pairs, Consts.UTF_8));
return httpPost;
}

/**
* 使用 MD5 加密请求数据。
*/
private String encrypt(String jsonRequest) {
return DigestUtils.md5Hex(jsonRequest + key);
}

/**
* http://www.example.com ==> [http, www.example.com] 。
*/
private String[] parseHost() {
if (host == null) {
return new String[] { "", "" };
}
String[] parts = StringUtils.split(host, "://");
if (parts.length != 2) {
return new String[] { "", "" };
}
return parts;
}

}



程序说明

1. InvokerMethod
该类比较简单,一个注解,它将作用于方法上,保留到运行期(这样才能通过反射获取其内容)。

2. HttpProxyFactoryBean
这个类比较奇特,也是这个解决方案的精华。
它实现了 FactoryBean 。 FactoryBean 是 Spring 类库的一个接口,它提供了三个方法需要实现:

T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();

和普通 Bean 不同,该类被配置为 Spring Bean 后,返回的不是 FactoryBean 本身,而是它的 getObject() 所返回的对象。 getObjectType() 将返回实例的类型,isSingleton() 可选择是否使用单例模式。

具体到本类,在 init 方法中,初始化了动态代理类 proxy ,这个 proxy 将作为 getObject() 的返回。 interfaceName 和 handler 将作为属性在 Spring 配置文件中注入:

<bean id="receiptQueryService" class="com.******.HttpProxyFactoryBean" init-method="init">
<property name="interfaceName" value="com.******.ReceiptQueryService"/>
<property name="handler" ref="httpInvocationHandler"/>
</bean>


ReceiptQueryService 大概长这个样子:

public interface ReceiptQueryService {

@InvokerMethod(method = InvokerMethod.HttpMethod.Get, path = "/xx/yy/zz")
ReceiptQueryResponse queryReceipts(ReceiptQueryRequest request);

}

现在,当我们调用 http 服务的时候,只需要写一个接口,在方法上加一个注解就可以了,加密等操作对程序员完全透明!

3. HttpInvocationHandler
我们在第二步中用到了一个 InvocationHandler 。我知道,它是 java.lang.reflect.Proxy 构造动态代理类的第三个参数:

public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)

它只有一个必须实现的接口:

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;


在我们 InvocationHandler 的实现类里,将通过反射获取方法的注解( path | get/post | timeout )和参数:

InvokerMethod invokerMethod = method.getAnnotation(InvokerMethod.class);
...
invokerMethod.method();
invokerMethod.path();
invokerMethod.timeout();
...

Object request = args[0];

这篇关于换一种口味实现 HttpClient的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/838190

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4