换一种口味实现 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

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q