Skip to content

Commit 0268356

Browse files
author
zhanq
committed
feat: add BaseResult and RateLimit classes for response header handling
1 parent 29416aa commit 0268356

2 files changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package cn.jiguang.sdk.bean;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnore;
4+
import lombok.Data;
5+
6+
import java.util.Collection;
7+
import java.util.Map;
8+
9+
/**
10+
* 所有Result的基类,包含HTTP响应头信息
11+
*/
12+
@Data
13+
public class BaseResult {
14+
15+
/**
16+
* 限流信息
17+
*/
18+
@JsonIgnore
19+
private RateLimit rateLimit;
20+
21+
/**
22+
* 从响应头中提取并设置相关字段
23+
*/
24+
public void setResponseHeaders(Map<String, Collection<String>> headers) {
25+
if (headers == null) {
26+
return;
27+
}
28+
29+
// 提取限流信息
30+
RateLimit rateLimit = new RateLimit();
31+
rateLimit.setLimit(extractIntHeader(headers, "x-rate-limit-limit"));
32+
rateLimit.setRemaining(extractIntHeader(headers, "x-rate-limit-remaining"));
33+
rateLimit.setReset(extractIntHeader(headers, "x-rate-limit-reset"));
34+
this.rateLimit = rateLimit;
35+
}
36+
37+
/**
38+
* 提取字符串类型的响应头
39+
*/
40+
private String extractStringHeader(Map<String, Collection<String>> headers, String headerName) {
41+
Collection<String> values = headers.get(headerName);
42+
if (values != null && !values.isEmpty()) {
43+
return values.iterator().next();
44+
}
45+
return null;
46+
}
47+
48+
/**
49+
* 提取整数类型的响应头
50+
*/
51+
private Integer extractIntHeader(Map<String, Collection<String>> headers, String headerName) {
52+
String value = extractStringHeader(headers, headerName);
53+
if (value != null) {
54+
try {
55+
return Integer.parseInt(value);
56+
} catch (NumberFormatException e) {
57+
return null;
58+
}
59+
}
60+
return null;
61+
}
62+
63+
}
64+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package cn.jiguang.sdk.bean;
2+
3+
import lombok.Data;
4+
5+
import java.io.Serializable;
6+
7+
/**
8+
* 限流信息
9+
*/
10+
@Data
11+
public class RateLimit implements Serializable {
12+
13+
/**
14+
* 当前 AppKey 一个时间窗口内可调用次数
15+
* 响应头: x-rate-limit-limit
16+
*/
17+
private Integer limit;
18+
19+
/**
20+
* 当前时间窗口剩余的可用次数
21+
* 响应头: x-rate-limit-remaining
22+
*/
23+
private Integer remaining;
24+
25+
/**
26+
* 距离时间窗口重置剩余的秒数
27+
* 响应头: x-rate-limit-reset
28+
*/
29+
private Integer reset;
30+
}
31+

0 commit comments

Comments
 (0)