312 lines
10 KiB
Dart
312 lines
10 KiB
Dart
/// 高级使用示例
|
|
/// 演示高性能解析、优化生成和性能监控
|
|
library;
|
|
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:swagger_generator_flutter/swagger_generator_flutter.dart';
|
|
|
|
void main() async {
|
|
print('🚀 高级使用示例');
|
|
print('=' * 50);
|
|
|
|
try {
|
|
await demonstrateHighPerformanceParsing();
|
|
await demonstrateOptimizedGeneration();
|
|
await demonstratePerformanceMonitoring();
|
|
await demonstrateCaching();
|
|
await demonstrateValidationAndErrorHandling();
|
|
|
|
print('\n🎉 高级使用示例完成!');
|
|
} catch (e, stackTrace) {
|
|
print('❌ 发生错误: $e');
|
|
print('堆栈跟踪: $stackTrace');
|
|
}
|
|
}
|
|
|
|
/// 演示高性能解析
|
|
Future<void> demonstrateHighPerformanceParsing() async {
|
|
print('\n📊 高性能解析演示');
|
|
print('-' * 30);
|
|
|
|
// 读取文档
|
|
final jsonString = await File('swagger.json').readAsString();
|
|
print('📖 文档大小: ${(jsonString.length / 1024).toStringAsFixed(2)}KB');
|
|
|
|
// 配置高性能解析器
|
|
final parser = PerformanceParser(
|
|
config: ParseConfig(
|
|
enablePerformanceStats: true,
|
|
enableParallelParsing: false, // 禁用并行解析避免类型转换问题
|
|
enableCaching: true,
|
|
maxConcurrency: 8,
|
|
enableMemoryOptimization: true,
|
|
),
|
|
);
|
|
|
|
// 解析文档
|
|
final stopwatch = Stopwatch()..start();
|
|
final document = await parser.parseDocument(jsonString);
|
|
stopwatch.stop();
|
|
|
|
// 显示解析结果
|
|
print('✅ 解析完成');
|
|
print(' - 解析时间: ${stopwatch.elapsedMilliseconds}ms');
|
|
print(' - 路径数: ${document.paths.length}');
|
|
print(' - 模型数: ${document.models.length}');
|
|
print(' - 服务器数: ${document.servers.length}');
|
|
|
|
// 显示性能统计
|
|
final stats = parser.lastStats;
|
|
if (stats != null) {
|
|
print('\n📈 性能统计:');
|
|
print(' - 总时间: ${stats.totalTime.inMilliseconds}ms');
|
|
print(' - 解析时间: ${stats.parseTime.inMilliseconds}ms');
|
|
print(' - 验证时间: ${stats.validationTime.inMilliseconds}ms');
|
|
print(' - 模型创建时间: ${stats.modelCreationTime.inMilliseconds}ms');
|
|
print(
|
|
' - 内存使用: ${(stats.memoryUsage / 1024 / 1024).toStringAsFixed(2)}MB');
|
|
print(' - 路径处理速度: ${stats.pathsPerSecond.toStringAsFixed(1)} paths/s');
|
|
print(' - 吞吐量: ${(stats.bytesPerSecond / 1024).toStringAsFixed(2)} KB/s');
|
|
}
|
|
|
|
// 显示缓存统计
|
|
final cacheStats = parser.getCacheStats();
|
|
print('\n🗄️ 缓存统计:');
|
|
print(' - 缓存大小: ${cacheStats['size']}');
|
|
print(' - 缓存键: ${(cacheStats['keys'] as List).length}');
|
|
}
|
|
|
|
/// 演示优化代码生成
|
|
Future<void> demonstrateOptimizedGeneration() async {
|
|
print('\n🔧 优化代码生成演示');
|
|
print('-' * 30);
|
|
|
|
// 解析文档
|
|
final jsonString = await File('swagger.json').readAsString();
|
|
final document = SwaggerDocument.fromJson(jsonDecode(jsonString));
|
|
|
|
// 创建优化生成器
|
|
final generator = OptimizedRetrofitGenerator(
|
|
className: 'AdvancedApiService',
|
|
generateModularApis: true,
|
|
generateBaseResult: true,
|
|
generatePagination: true,
|
|
generateFileUpload: true,
|
|
baseResultType: 'ApiResult',
|
|
pageResultType: 'PagedResult',
|
|
);
|
|
|
|
// 生成代码
|
|
final stopwatch = Stopwatch()..start();
|
|
final generatedCode = generator.generateFromDocument(document);
|
|
stopwatch.stop();
|
|
|
|
print('✅ 代码生成完成');
|
|
print(' - 生成时间: ${stopwatch.elapsedMilliseconds}ms');
|
|
print(' - 代码大小: ${(generatedCode.length / 1024).toStringAsFixed(2)}KB');
|
|
print(' - 代码行数: ${generatedCode.split('\n').length}');
|
|
|
|
// 检查生成的特性
|
|
final features = <String>[];
|
|
if (generatedCode.contains('class ApiResult')) features.add('基础响应类型');
|
|
if (generatedCode.contains('class PagedResult')) features.add('分页支持');
|
|
if (generatedCode.contains('MultipartFile')) features.add('文件上传');
|
|
if (generatedCode.contains('class ApiUtils')) features.add('工具类');
|
|
|
|
print(' - 生成特性: ${features.join(', ')}');
|
|
|
|
// 保存代码
|
|
final outputFile = File('example/generated/advanced_api_service.dart');
|
|
await outputFile.writeAsString(generatedCode);
|
|
print(' - 保存位置: ${outputFile.path}');
|
|
}
|
|
|
|
/// 演示性能监控
|
|
Future<void> demonstratePerformanceMonitoring() async {
|
|
print('\n📊 性能监控演示');
|
|
print('-' * 30);
|
|
|
|
// 解析文档
|
|
final jsonString = await File('swagger.json').readAsString();
|
|
final document = SwaggerDocument.fromJson(jsonDecode(jsonString));
|
|
|
|
// 创建性能生成器
|
|
final generator = PerformanceGenerator(
|
|
maxConcurrency: 4,
|
|
enableCaching: true,
|
|
enableIncremental: true,
|
|
enableParallel: true,
|
|
);
|
|
|
|
// 生成代码
|
|
final generatedCode = await generator.generateFromDocument(document);
|
|
|
|
// 获取性能统计
|
|
final stats = generator.getStats();
|
|
print('📈 生成性能统计:');
|
|
print(' - 总任务数: ${stats.totalTasks}');
|
|
print(' - 完成任务数: ${stats.completedTasks}');
|
|
print(' - 失败任务数: ${stats.failedTasks}');
|
|
print(' - 成功率: ${(stats.successRate * 100).toStringAsFixed(1)}%');
|
|
print(' - 总时间: ${stats.totalTime.inMilliseconds}ms');
|
|
print(' - 平均任务时间: ${stats.averageTaskTime.inMilliseconds}ms');
|
|
print(' - 生成行数: ${stats.linesGenerated}');
|
|
print(' - 生成字节数: ${stats.bytesGenerated}');
|
|
print(' - 并行效率: ${(stats.parallelEfficiency * 100).toStringAsFixed(1)}%');
|
|
print(' - 生成速度: ${stats.linesPerSecond.toStringAsFixed(1)} lines/s');
|
|
|
|
// 获取缓存统计
|
|
final cacheStats = generator.getCacheStats();
|
|
print('\n🗄️ 生成器缓存统计:');
|
|
print(' - 总请求: ${cacheStats.totalRequests}');
|
|
print(' - 缓存命中: ${cacheStats.hits}');
|
|
print(' - 缓存未命中: ${cacheStats.misses}');
|
|
print(' - 命中率: ${(cacheStats.hitRate * 100).toStringAsFixed(1)}%');
|
|
print(' - 缓存大小: ${cacheStats.size}/${cacheStats.maxSize}');
|
|
print(' - 平均访问时间: ${cacheStats.averageAccessTime.inMicroseconds}μs');
|
|
}
|
|
|
|
/// 演示缓存功能
|
|
Future<void> demonstrateCaching() async {
|
|
print('\n🗄️ 缓存功能演示');
|
|
print('-' * 30);
|
|
|
|
// 创建智能缓存
|
|
final cache = SmartCache<String>(
|
|
maxSize: 100,
|
|
strategy: CacheStrategy.smart,
|
|
defaultTtl: Duration(minutes: 30),
|
|
);
|
|
|
|
// 添加一些测试数据
|
|
cache.put('user:1', '{"id": 1, "name": "Alice"}');
|
|
cache.put('user:2', '{"id": 2, "name": "Bob"}');
|
|
cache.put('user:3', '{"id": 3, "name": "Charlie"}');
|
|
|
|
// 模拟访问模式
|
|
for (int i = 0; i < 10; i++) {
|
|
cache.get('user:1'); // 频繁访问
|
|
}
|
|
for (int i = 0; i < 5; i++) {
|
|
cache.get('user:2'); // 中等访问
|
|
}
|
|
cache.get('user:3'); // 少量访问
|
|
|
|
// 获取缓存统计
|
|
final stats = cache.getStats();
|
|
print('📊 缓存统计:');
|
|
print(' - 总请求: ${stats.totalRequests}');
|
|
print(' - 命中: ${stats.hits}');
|
|
print(' - 未命中: ${stats.misses}');
|
|
print(' - 命中率: ${(stats.hitRate * 100).toStringAsFixed(1)}%');
|
|
print(' - 缓存大小: ${stats.size}/${stats.maxSize}');
|
|
print(' - 填充率: ${(stats.fillRate * 100).toStringAsFixed(1)}%');
|
|
|
|
// 显示访问统计
|
|
print('\n📈 访问统计:');
|
|
stats.keyAccessCounts.forEach((key, count) {
|
|
print(' - $key: $count 次访问');
|
|
});
|
|
|
|
// 演示缓存预热
|
|
print('\n🔥 缓存预热演示:');
|
|
await cache.warmUp({
|
|
'config:app': () async => '{"theme": "dark", "language": "zh"}',
|
|
'config:api': () async => '{"timeout": 30000, "retries": 3}',
|
|
});
|
|
|
|
print(' - 预热完成,缓存大小: ${cache.getStats().size}');
|
|
}
|
|
|
|
/// 演示验证和错误处理
|
|
Future<void> demonstrateValidationAndErrorHandling() async {
|
|
print('\n✅ 验证和错误处理演示');
|
|
print('-' * 30);
|
|
|
|
// 创建一个有问题的文档
|
|
final problematicDoc = {
|
|
'openapi': '3.0.3',
|
|
'info': {
|
|
'title': 'Problematic API',
|
|
'version': '1.0.0',
|
|
},
|
|
'paths': {
|
|
'/users/{id}': {
|
|
'get': {
|
|
'summary': 'Get user',
|
|
'responses': {
|
|
'200': {
|
|
'description': 'Success',
|
|
},
|
|
},
|
|
// 缺少路径参数声明
|
|
},
|
|
},
|
|
'invalid-path': {
|
|
// 无效的路径格式
|
|
'get': {
|
|
'summary': 'Invalid path',
|
|
'responses': {
|
|
'200': {
|
|
'description': 'Success',
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
};
|
|
|
|
final jsonString = jsonEncode(problematicDoc);
|
|
final document = SwaggerDocument.fromJson(jsonDecode(jsonString));
|
|
|
|
// 创建验证器
|
|
final validator = EnhancedValidator(
|
|
includeWarnings: true,
|
|
);
|
|
|
|
// 验证文档
|
|
final isValid = validator.validateDocument(document);
|
|
print('📋 验证结果: ${isValid ? "通过" : "失败"}');
|
|
|
|
// 获取错误统计
|
|
final errorStats = validator.errorReporter.getErrorStatistics();
|
|
print('\n📊 错误统计:');
|
|
errorStats.forEach((severity, count) {
|
|
print(' - ${severity.displayName}: $count');
|
|
});
|
|
|
|
// 显示详细错误
|
|
final errors = validator.errorReporter.errors;
|
|
if (errors.isNotEmpty) {
|
|
print('\n❌ 详细错误:');
|
|
for (int i = 0; i < errors.length && i < 5; i++) {
|
|
final error = errors[i];
|
|
print(' ${i + 1}. ${error.severity.emoji} ${error.title}');
|
|
print(' 位置: ${error.location.jsonPath}');
|
|
print(' 描述: ${error.description}');
|
|
if (error.suggestions.isNotEmpty) {
|
|
print(' 建议: ${error.suggestions.first.description}');
|
|
}
|
|
print('');
|
|
}
|
|
}
|
|
|
|
// 生成错误报告
|
|
final report = validator.errorReporter.generateReport(
|
|
includeStatistics: true,
|
|
groupByCategory: true,
|
|
);
|
|
|
|
// 保存错误报告
|
|
final reportFile = File('example/generated/validation_report.txt');
|
|
await reportFile.writeAsString(report);
|
|
print('📄 错误报告已保存到: ${reportFile.path}');
|
|
|
|
// 生成 JSON 格式报告
|
|
final jsonReport = validator.errorReporter.generateJsonReport();
|
|
final jsonReportFile = File('example/generated/validation_report.json');
|
|
await jsonReportFile.writeAsString(jsonReport);
|
|
print('📄 JSON 报告已保存到: ${jsonReportFile.path}');
|
|
}
|