1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
| /**
* 组件接口 - HTTP请求
*/
public interface HttpRequest {
String execute();
String getRequestInfo();
}
/**
* 具体组件 - 基础HTTP请求
*/
public class BasicHttpRequest implements HttpRequest {
private String url;
private String method;
private String body;
public BasicHttpRequest(String url, String method, String body) {
this.url = url;
this.method = method;
this.body = body;
}
@Override
public String execute() {
// 模拟HTTP请求执行
return "Response from " + url + " using " + method;
}
@Override
public String getRequestInfo() {
return method + " " + url;
}
public String getUrl() { return url; }
public String getMethod() { return method; }
public String getBody() { return body; }
}
/**
* 装饰器抽象类
*/
public abstract class HttpRequestDecorator implements HttpRequest {
protected HttpRequest request;
public HttpRequestDecorator(HttpRequest request) {
this.request = request;
}
@Override
public String execute() {
return request.execute();
}
@Override
public String getRequestInfo() {
return request.getRequestInfo();
}
}
/**
* 具体装饰器 - 认证装饰器
*/
public class AuthenticationDecorator extends HttpRequestDecorator {
private String authType;
private String credentials;
public AuthenticationDecorator(HttpRequest request, String authType, String credentials) {
super(request);
this.authType = authType;
this.credentials = credentials;
}
@Override
public String execute() {
authenticate();
return request.execute();
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [Auth: " + authType + "]";
}
private void authenticate() {
System.out.println("🔐 执行" + authType + "认证");
switch (authType.toLowerCase()) {
case "bearer":
System.out.println(" 添加 Authorization: Bearer " + credentials);
break;
case "basic":
System.out.println(" 添加 Authorization: Basic " +
java.util.Base64.getEncoder().encodeToString(credentials.getBytes()));
break;
case "api_key":
System.out.println(" 添加 X-API-Key: " + credentials);
break;
default:
System.out.println(" 使用自定义认证: " + authType);
}
}
}
/**
* 具体装饰器 - 缓存装饰器
*/
public class CacheDecorator extends HttpRequestDecorator {
private static Map<String, String> cache = new HashMap<>();
private int cacheExpireMinutes;
public CacheDecorator(HttpRequest request, int cacheExpireMinutes) {
super(request);
this.cacheExpireMinutes = cacheExpireMinutes;
}
@Override
public String execute() {
String cacheKey = generateCacheKey();
// 检查缓存
if (cache.containsKey(cacheKey)) {
System.out.println("💾 缓存命中: " + cacheKey);
return "CACHED: " + cache.get(cacheKey);
}
// 执行请求
System.out.println("🌐 缓存未命中,执行网络请求");
String response = request.execute();
// 存入缓存
cache.put(cacheKey, response);
System.out.println("💾 结果已缓存,过期时间: " + cacheExpireMinutes + " 分钟");
return response;
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [Cache: " + cacheExpireMinutes + "min]";
}
private String generateCacheKey() {
return request.getRequestInfo().hashCode() + "";
}
public static void clearCache() {
cache.clear();
System.out.println("💾 缓存已清空");
}
}
/**
* 具体装饰器 - 重试装饰器
*/
public class RetryDecorator extends HttpRequestDecorator {
private int maxRetries;
private int retryDelayMs;
public RetryDecorator(HttpRequest request, int maxRetries, int retryDelayMs) {
super(request);
this.maxRetries = maxRetries;
this.retryDelayMs = retryDelayMs;
}
@Override
public String execute() {
int attempt = 1;
while (attempt <= maxRetries) {
try {
System.out.println("🔄 第 " + attempt + " 次请求尝试");
// 模拟网络请求可能失败
if (Math.random() < 0.3 && attempt < maxRetries) { // 30%失败率
throw new RuntimeException("网络请求失败");
}
String response = request.execute();
if (attempt > 1) {
System.out.println("✅ 重试成功");
}
return response;
} catch (Exception e) {
System.out.println("❌ 第 " + attempt + " 次尝试失败: " + e.getMessage());
if (attempt == maxRetries) {
System.out.println("💥 达到最大重试次数,请求最终失败");
throw new RuntimeException("请求失败,已重试 " + maxRetries + " 次");
}
// 等待后重试
try {
Thread.sleep(retryDelayMs);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
attempt++;
}
}
throw new RuntimeException("重试逻辑异常终止");
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [Retry: " + maxRetries + "x]";
}
}
/**
* 具体装饰器 - 日志装饰器
*/
public class RequestLoggingDecorator extends HttpRequestDecorator {
private String logLevel;
public RequestLoggingDecorator(HttpRequest request, String logLevel) {
super(request);
this.logLevel = logLevel;
}
@Override
public String execute() {
long startTime = System.currentTimeMillis();
log("开始执行请求: " + request.getRequestInfo());
try {
String response = request.execute();
long duration = System.currentTimeMillis() - startTime;
log("请求成功完成,耗时: " + duration + "ms");
log("响应预览: " + response.substring(0, Math.min(50, response.length())) + "...");
return response;
} catch (Exception e) {
long duration = System.currentTimeMillis() - startTime;
log("请求失败,耗时: " + duration + "ms,错误: " + e.getMessage());
throw e;
}
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [Log: " + logLevel + "]";
}
private void log(String message) {
String timestamp = java.time.LocalTime.now().toString();
String level = logLevel.toUpperCase();
System.out.println("[" + level + " " + timestamp + "] " + message);
}
}
/**
* 具体装饰器 - 速率限制装饰器
*/
public class RateLimitDecorator extends HttpRequestDecorator {
private static Map<String, Long> lastRequestTime = new HashMap<>();
private long minIntervalMs;
public RateLimitDecorator(HttpRequest request, long minIntervalMs) {
super(request);
this.minIntervalMs = minIntervalMs;
}
@Override
public String execute() {
String rateLimitKey = getRateLimitKey();
long currentTime = System.currentTimeMillis();
Long lastTime = lastRequestTime.get(rateLimitKey);
if (lastTime != null) {
long timeSinceLastRequest = currentTime - lastTime;
if (timeSinceLastRequest < minIntervalMs) {
long waitTime = minIntervalMs - timeSinceLastRequest;
System.out.println("⏱️ 速率限制:需要等待 " + waitTime + "ms");
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("等待被中断");
}
}
}
// 更新最后请求时间
lastRequestTime.put(rateLimitKey, System.currentTimeMillis());
return request.execute();
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [RateLimit: " + minIntervalMs + "ms]";
}
private String getRateLimitKey() {
// 简化:使用请求信息作为限流键
return request.getRequestInfo();
}
}
/**
* 具体装饰器 - 性能监控装饰器
*/
public class PerformanceMonitoringDecorator extends HttpRequestDecorator {
private static Map<String, List<Long>> performanceStats = new HashMap<>();
public PerformanceMonitoringDecorator(HttpRequest request) {
super(request);
}
@Override
public String execute() {
long startTime = System.nanoTime();
try {
String response = request.execute();
long endTime = System.nanoTime();
long durationMs = (endTime - startTime) / 1_000_000;
recordPerformance(durationMs);
return response;
} catch (Exception e) {
long endTime = System.nanoTime();
long durationMs = (endTime - startTime) / 1_000_000;
recordPerformance(durationMs);
throw e;
}
}
@Override
public String getRequestInfo() {
return request.getRequestInfo() + " [Monitor]";
}
private void recordPerformance(long durationMs) {
String key = request.getRequestInfo();
performanceStats.computeIfAbsent(key, k -> new ArrayList<>()).add(durationMs);
System.out.println("📊 性能记录: " + durationMs + "ms");
}
public static void printPerformanceStats() {
System.out.println("\n📊 === 性能统计报告 ===");
for (Map.Entry<String, List<Long>> entry : performanceStats.entrySet()) {
List<Long> times = entry.getValue();
if (!times.isEmpty()) {
double avgTime = times.stream().mapToLong(Long::longValue).average().orElse(0.0);
long minTime = times.stream().mapToLong(Long::longValue).min().orElse(0);
long maxTime = times.stream().mapToLong(Long::longValue).max().orElse(0);
System.out.println("请求: " + entry.getKey());
System.out.println(" 调用次数: " + times.size());
System.out.println(" 平均耗时: " + String.format("%.2f", avgTime) + "ms");
System.out.println(" 最小耗时: " + minTime + "ms");
System.out.println(" 最大耗时: " + maxTime + "ms");
}
}
}
}
// 网络请求装饰器演示
public class HttpRequestDecoratorDemo {
public static void main(String[] args) {
System.out.println("=== 网络请求装饰器演示 ===");
System.out.println("\n=== 基础请求 ===");
HttpRequest basicRequest = new BasicHttpRequest("https://api.example.com/users", "GET", null);
System.out.println("请求信息: " + basicRequest.getRequestInfo());
System.out.println("响应: " + basicRequest.execute());
System.out.println("\n=== 带认证的请求 ===");
HttpRequest authRequest = new AuthenticationDecorator(
new BasicHttpRequest("https://api.example.com/private", "GET", null),
"bearer",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
);
System.out.println("请求信息: " + authRequest.getRequestInfo());
System.out.println("响应: " + authRequest.execute());
System.out.println("\n=== 带缓存的请求 ===");
HttpRequest cachedRequest = new CacheDecorator(
new BasicHttpRequest("https://api.example.com/products", "GET", null),
30 // 30分钟缓存
);
System.out.println("第一次请求:");
System.out.println("请求信息: " + cachedRequest.getRequestInfo());
System.out.println("响应: " + cachedRequest.execute());
System.out.println("\n第二次请求:");
System.out.println("响应: " + cachedRequest.execute());
System.out.println("\n=== 复杂请求链 ===");
// 认证 + 缓存 + 重试 + 日志 + 性能监控
HttpRequest complexRequest = new PerformanceMonitoringDecorator(
new RequestLoggingDecorator(
new RetryDecorator(
new CacheDecorator(
new AuthenticationDecorator(
new BasicHttpRequest("https://api.example.com/orders", "POST", "{\"item\":\"laptop\"}"),
"api_key",
"abc123def456"
),
15 // 15分钟缓存
),
3, // 最多重试3次
1000 // 重试间隔1秒
),
"info"
)
);
System.out.println("复杂请求信息: " + complexRequest.getRequestInfo());
try {
String response = complexRequest.execute();
System.out.println("最终响应: " + response);
} catch (Exception e) {
System.out.println("请求失败: " + e.getMessage());
}
System.out.println("\n=== 速率限制演示 ===");
HttpRequest rateLimitedRequest = new RateLimitDecorator(
new BasicHttpRequest("https://api.example.com/search", "GET", null),
2000 // 2秒间隔
);
// 连续发送多个请求
for (int i = 1; i <= 3; i++) {
System.out.println("\n第 " + i + " 个请求:");
long startTime = System.currentTimeMillis();
rateLimitedRequest.execute();
long duration = System.currentTimeMillis() - startTime;
System.out.println("实际耗时: " + duration + "ms");
}
System.out.println("\n=== 动态构建请求装饰链 ===");
HttpRequest dynamicRequest = new BasicHttpRequest("https://api.example.com/analytics", "GET", null);
System.out.println("基础请求: " + dynamicRequest.getRequestInfo());
// 逐步添加装饰器
dynamicRequest = new PerformanceMonitoringDecorator(dynamicRequest);
System.out.println("添加性能监控: " + dynamicRequest.getRequestInfo());
dynamicRequest = new CacheDecorator(dynamicRequest, 60);
System.out.println("添加缓存: " + dynamicRequest.getRequestInfo());
dynamicRequest = new AuthenticationDecorator(dynamicRequest, "basic", "user:pass");
System.out.println("添加认证: " + dynamicRequest.getRequestInfo());
dynamicRequest = new RequestLoggingDecorator(dynamicRequest, "debug");
System.out.println("添加日志: " + dynamicRequest.getRequestInfo());
// 执行最终请求
System.out.println("\n执行动态构建的请求:");
dynamicRequest.execute();
System.out.println("\n=== 批量请求测试 ===");
String[] endpoints = {
"https://api.example.com/users",
"https://api.example.com/products",
"https://api.example.com/orders"
};
for (String endpoint : endpoints) {
HttpRequest batchRequest = new PerformanceMonitoringDecorator(
new CacheDecorator(
new BasicHttpRequest(endpoint, "GET", null),
45
)
);
System.out.println("\n请求: " + endpoint);
batchRequest.execute();
}
// 清除缓存
CacheDecorator.clearCache();
// 显示性能统计
PerformanceMonitoringDecorator.printPerformanceStats();
System.out.println("\n观察:可以灵活组合各种中间件功能,构建强大的HTTP客户端!");
}
}
|