详情介绍
2025/9/7大约 4 分钟
详情介绍
组件工作逻辑
请求处理流程
异常处理流程
异常处理说明:
- 所有异常统一抛出
GatewayException或其子类 - IO异常、网络异常、响应解析异常都会被包装为
GatewayException AuthException和TimeoutException为预留异常类,当前版本未使用
文件详细说明
1. GatewayClient
路径: top.codelong.sendsdk.client
作用: 网关客户端核心类,提供HTTP请求API
关键方法:
// GET请求
public String get(String path, Map<String, Object> params) throws GatewayException
// POST请求
public String post(String path, Map<String, Object> params, Object body) throws GatewayException
// PUT请求
public String put(String path, Map<String, Object> params, Object body) throws GatewayException
// DELETE请求
public String delete(String path, Map<String, Object> params) throws GatewayException核心逻辑:
private String execute(HttpMethod method, String path,
Map<String, Object> params, Object body) throws GatewayException {
// 1. 构建完整URL
String url = buildUrl(path, params);
// 2. 创建HTTP请求
HttpUriRequest request = createRequest(method, url, body);
// 3. 设置认证头
setAuthHeader(request);
// 4. 执行请求
HttpResponse response = httpClient.execute(request);
// 5. 处理响应
return handleResponse(response);
}
private String handleResponse(HttpResponse response) throws IOException {
// 1. 检查HTTP状态码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
throw new GatewayException("网关返回错误状态码: " + statusCode);
}
// 2. 获取响应体
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new GatewayException("网关返回空响应");
}
// 3. 解析JSON响应
String responseBody = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseBody);
// 4. 验证响应格式
if (!jsonObject.containsKey("code") || !jsonObject.containsKey("msg")) {
throw new GatewayException("网关返回无效响应");
}
// 5. 检查业务状态码
if (!jsonObject.getInt("code").equals(1)) {
throw new GatewayException("网关返回错误: " + jsonObject.getStr("msg"));
}
// 6. 返回业务数据
return jsonObject.getStr("data");
}响应格式说明:
- HTTP状态码必须在 200-299 范围内
- 响应体必须是 JSON 格式,包含
code、msg、data三个字段 - 业务状态码
code必须为 1 表示成功 - 返回值为
data字段的值(字符串格式)
2. GatewaySDKProperties
路径: top.codelong.sendsdk.config
作用: SDK配置属性类,管理网关地址、认证信息等
配置项:
@ConfigurationProperties(prefix = "api.gateway.sdk")
public class GatewaySDKProperties {
private String baseUrl; // 网关基础URL
private String safeKey; // 安全密钥
private String safeSecret; // 安全凭证
private int connectTimeout = 5000; // 连接超时(毫秒)
private int socketTimeout = 10000; // 读取超时(毫秒)
private int maxConnections = 100; // 最大连接数
}3. JwtUtils
路径: top.codelong.sendsdk.utils
作用: JWT令牌生成工具类
关键逻辑:
public String generateToken(String key, String secret) {
// 1. 设置过期时间(30天)
Date expireDate = new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME);
// 2. 创建HMAC256算法
Algorithm algorithm = Algorithm.HMAC256(secret);
// 3. 构建JWT Token
return JWT.create()
.withIssuedAt(new Date())
.withExpiresAt(expireDate)
.withClaim("safe-key", key)
.sign(algorithm);
}Token特性:
- 有效期:30天
- 算法:HMAC256
- 包含声明:safe-key(安全密钥)
- 包含签发时间和过期时间
4. HttpClientFactory
路径: top.codelong.sendsdk.client
作用: HTTP客户端工厂类,负责创建和配置HttpClient
关键配置:
public static CloseableHttpClient createHttpClient(GatewaySDKProperties properties) {
// 1. 创建连接管理器
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(properties.getMaxConnections());
cm.setDefaultMaxPerRoute(properties.getMaxConnections() / 2);
cm.setValidateAfterInactivity(30_000); // 30秒后验证连接
// 2. 设置请求配置
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(properties.getConnectTimeout())
.setSocketTimeout(properties.getSocketTimeout())
.build();
// 3. 创建HttpClient
return HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(config)
.evictIdleConnections(60L, TimeUnit.SECONDS) // 60秒清理空闲连接
.build();
}连接池特性:
- 支持连接复用
- 自动清理空闲连接(60秒)
- 30秒后验证连接有效性
- 可配置的连接超时和读取超时
- 支持高并发请求
- 详细的日志记录
5. GatewaySDKAutoConfiguration(推荐使用)
路径: top.codelong.sendsdk.config
作用: SDK自动配置类,创建SDK所需的Bean(推荐使用)
关键配置:
@Configuration
@ConditionalOnClass(name = "org.apache.http.client.HttpClient")
@EnableConfigurationProperties(GatewaySDKProperties.class)
@ConditionalOnProperty(prefix = "api.gateway.sdk", name = "base-url")
public class GatewaySDKAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public JwtUtils jwtUtils() {
return new JwtUtils();
}
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
@ConditionalOnMissingBean
public CloseableHttpClient httpClient(GatewaySDKProperties properties) {
return HttpClientFactory.createHttpClient(properties);
}
@Bean
@ConditionalOnMissingBean
public GatewayClient gatewayClient(
GatewaySDKProperties properties,
ObjectMapper objectMapper,
JwtUtils jwtUtils,
CloseableHttpClient httpClient) {
return new GatewayClient(properties, objectMapper, jwtUtils, httpClient);
}
}特点:
- 使用
@ConditionalOnClass确保 HttpClient 在类路径中 - 使用
@ConditionalOnProperty确保配置了api.gateway.sdk.base-url - 使用
HttpClientFactory创建完整配置的 HttpClient - 支持更灵活的条件装配
6. 异常体系
GatewayException - 网关异常基类
public class GatewayException extends RuntimeException {
public GatewayException(String message) {
super(message);
}
public GatewayException(String message, Throwable cause) {
super(message, cause);
}
}AuthException - 认证异常
public class AuthException extends GatewayException {
public AuthException(String message) {
super(message);
}
}TimeoutException - 超时异常
public class TimeoutException extends GatewayException {
public TimeoutException(String message) {
super(message);
}
}7. Result
路径: top.codelong.sendsdk.common
作用: 统一响应结果封装类
数据结构:
public class Result<T> implements Serializable {
private Integer code; // 状态码 (1:成功, 0:失败)
private String msg; // 消息
private T data; // 业务数据
}工厂方法:
// 成功响应
Result.success(); // code=1, msg="", data=null
Result.success(data); // code=1, msg="", data=data
// 失败响应
Result.error(msg); // code=0, msg=msg, data=null状态码说明:
code = 1: 请求成功code = 0: 请求失败msg: 错误消息或提示信息data: 业务数据(成功时返回,失败时为 null)
辅助方法:
// 判断是否成功
boolean isSuccess = result.isSuccess(); // 等价于 result.getCode() == 1