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 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
| using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.ResourceManagement;
public class CustomCacheStrategySystem : MonoBehaviour { [Header("自定义缓存策略配置")] public bool enableCustomCaching = true; public CacheStrategyType cacheStrategy = CacheStrategyType.LRU; public long maxCacheSize = 100 * 1024 * 1024; public float cacheTimeout = 3600f; public bool enableDiskCaching = true; public bool enableMemoryCaching = true; public enum CacheStrategyType { LRU, LFU, FIFO, Priority, Hybrid } [System.Serializable] public class CacheEntry { public string key; public object data; public DateTime lastAccessTime; public DateTime creationTime; public long size; public int accessCount; public float priority; public string resourceType; public CacheEntry(string key, object data, long size, string type) { this.key = key; this.data = data; this.size = size; this.resourceType = type; this.lastAccessTime = DateTime.Now; this.creationTime = DateTime.Now; this.accessCount = 1; this.priority = 1.0f; } } public class CustomCacheManager { private Dictionary<string, CacheEntry> memoryCache = new Dictionary<string, CacheEntry>(); private LinkedList<string> lruList = new LinkedList<string>(); private Dictionary<string, LinkedListNode<string>> lruMap = new Dictionary<string, LinkedListNode<string>>(); private long currentMemorySize = 0; private long maxCacheSize; private float cacheTimeout; private CacheStrategyType strategy; private bool enableDiskCaching; private bool enableMemoryCaching; public CustomCacheManager(long maxSize, float timeout, CacheStrategyType cacheStrategy, bool diskCaching, bool memoryCaching) { maxCacheSize = maxSize; cacheTimeout = timeout; strategy = cacheStrategy; enableDiskCaching = diskCaching; enableMemoryCaching = memoryCaching; } public bool AddToCache(string key, object data, long size, string resourceType) { if (!enableMemoryCaching) return false; if (memoryCache.ContainsKey(key)) { var entry = memoryCache[key]; currentMemorySize -= entry.size; entry.data = data; entry.size = size; entry.lastAccessTime = DateTime.Now; entry.accessCount++; currentMemorySize += size; UpdateCacheStrategy(key); return true; } if (currentMemorySize + size > maxCacheSize) { if (!EvictCacheEntries(size)) { return false; } } var newEntry = new CacheEntry(key, data, size, resourceType); memoryCache[key] = newEntry; currentMemorySize += size; UpdateCacheStrategy(key); if (enableDiskCaching) { SaveToDisk(key, data, resourceType); } return true; } public bool TryGetFromCache(string key, out object data) { data = null; if (!enableMemoryCaching) return false; if (memoryCache.ContainsKey(key)) { var entry = memoryCache[key]; if ((DateTime.Now - entry.lastAccessTime).TotalSeconds > cacheTimeout) { RemoveFromCache(key); return false; } entry.lastAccessTime = DateTime.Now; entry.accessCount++; UpdateCacheStrategy(key); data = entry.data; return true; } if (enableDiskCaching && File.Exists(GetDiskCachePath(key))) { data = LoadFromDisk(key); if (data != null) { long size = GetObjectSize(data); AddToCache(key, data, size, GetObjectType(data)); return true; } } return false; } public bool RemoveFromCache(string key) { if (memoryCache.ContainsKey(key)) { var entry = memoryCache[key]; currentMemorySize -= entry.size; if (lruMap.ContainsKey(key)) { lruList.Remove(lruMap[key]); lruMap.Remove(key); } memoryCache.Remove(key); if (enableDiskCaching) { DeleteFromDisk(key); } return true; } return false; } public void CleanupExpiredCache() { var keysToRemove = new List<string>(); foreach (var kvp in memoryCache) { if ((DateTime.Now - kvp.Value.lastAccessTime).TotalSeconds > cacheTimeout) { keysToRemove.Add(kvp.Key); } } foreach (string key in keysToRemove) { RemoveFromCache(key); } } private bool EvictCacheEntries(long requiredSize) { long freedSize = 0; while (currentMemorySize + requiredSize > maxCacheSize && memoryCache.Count > 0) { string keyToEvict = null; switch (strategy) { case CacheStrategyType.LRU: keyToEvict = GetLRUEvictionCandidate(); break; case CacheStrategyType.LFU: keyToEvict = GetLFUEvictionCandidate(); break; case CacheStrategyType.FIFO: keyToEvict = GetFIFOEvictionCandidate(); break; case CacheStrategyType.Priority: keyToEvict = GetPriorityEvictionCandidate(); break; case CacheStrategyType.Hybrid: keyToEvict = GetHybridEvictionCandidate(); break; } if (keyToEvict == null) { return false; } var entry = memoryCache[keyToEvict]; freedSize += entry.size; RemoveFromCache(keyToEvict); } return true; } private string GetLRUEvictionCandidate() { if (lruList.First != null) { return lruList.First.Value; } foreach (var kvp in memoryCache) { return kvp.Key; } return null; } private string GetLFUEvictionCandidate() { string candidateKey = null; int minAccessCount = int.MaxValue; foreach (var kvp in memoryCache) { if (kvp.Value.accessCount < minAccessCount) { minAccessCount = kvp.Value.accessCount; candidateKey = kvp.Key; } } return candidateKey; } private string GetFIFOEvictionCandidate() { string candidateKey = null; DateTime earliestTime = DateTime.MaxValue; foreach (var kvp in memoryCache) { if (kvp.Value.creationTime < earliestTime) { earliestTime = kvp.Value.creationTime; candidateKey = kvp.Key; } } return candidateKey; } private string GetPriorityEvictionCandidate() { string candidateKey = null; float minPriority = float.MaxValue; foreach (var kvp in memoryCache) { if (kvp.Value.priority < minPriority) { minPriority = kvp.Value.priority; candidateKey = kvp.Key; } } return candidateKey; } private string GetHybridEvictionCandidate() { string candidateKey = null; double minScore = double.MaxValue; foreach (var kvp in memoryCache) { var entry = kvp.Value; double score = (entry.accessCount * 0.3) + ((DateTime.Now - entry.lastAccessTime).TotalMinutes * 0.7); if (score < minScore) { minScore = score; candidateKey = kvp.Key; } } return candidateKey; } private void UpdateCacheStrategy(string key) { switch (strategy) { case CacheStrategyType.LRU: UpdateLRU(key); break; } } private void UpdateLRU(string key) { if (lruMap.ContainsKey(key)) { lruList.Remove(lruMap[key]); } var node = lruList.AddLast(key); lruMap[key] = node; } private void SaveToDisk(string key, object data, string resourceType) { try { string path = GetDiskCachePath(key); string directory = Path.GetDirectoryName(path); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(path, key); } catch (Exception ex) { Debug.LogError($"保存到磁盘缓存失败: {ex.Message}"); } } private object LoadFromDisk(string key) { try { string path = GetDiskCachePath(key); if (File.Exists(path)) { return new object(); } } catch (Exception ex) { Debug.LogError($"从磁盘缓存加载失败: {ex.Message}"); } return null; } private void DeleteFromDisk(string key) { try { string path = GetDiskCachePath(key); if (File.Exists(path)) { File.Delete(path); } } catch (Exception ex) { Debug.LogError($"删除磁盘缓存失败: {ex.Message}"); } } private string GetDiskCachePath(string key) { string hash = key.GetHashCode().ToString("x8"); string subDir = hash.Substring(0, 2); return Path.Combine(Application.persistentDataPath, "Cache", subDir, hash + ".cache"); } private long GetObjectSize(object obj) { return 1024; } private string GetObjectType(object obj) { return obj?.GetType().Name ?? "Unknown"; } public string GetCacheStats() { var stats = new System.Text.StringBuilder(); stats.AppendLine("缓存统计:"); stats.AppendLine($" 条目数量: {memoryCache.Count}"); stats.AppendLine($" 当前大小: {FormatBytes(currentMemorySize)}"); stats.AppendLine($" 最大大小: {FormatBytes(maxCacheSize)}"); stats.AppendLine($" 使用率: {(float)currentMemorySize / maxCacheSize * 100:F1}%"); stats.AppendLine($" 策略: {strategy}"); stats.AppendLine($" 磁盘缓存: {enableDiskCaching}"); stats.AppendLine($" 内存缓存: {enableMemoryCaching}"); return stats.ToString(); } } [System.Serializable] public class CacheAnalysisResult { public CacheStrategyType strategy; public int hitCount; public int missCount; public float hitRate; public long totalSize; public int entryCount; public float avgAccessTime; public List<string> evictionStats; } private CustomCacheManager cacheManager; private int hitCount = 0; private int missCount = 0; private List<float> accessTimes = new List<float>(); void Start() { Debug.Log("自定义缓存策略系统启动"); if (enableCustomCaching) { InitializeCacheSystem(); } } private void InitializeCacheSystem() { cacheManager = new CustomCacheManager(maxCacheSize, cacheTimeout, cacheStrategy, enableDiskCaching, enableMemoryCaching); Debug.Log($"缓存系统初始化完成,策略: {cacheStrategy}, 大小限制: {FormatBytes(maxCacheSize)}"); } public CacheAnalysisResult TestCachePerformance(int operationCount = 1000) { var result = new CacheAnalysisResult { strategy = cacheStrategy, hitCount = 0, missCount = 0, evictionStats = new List<string>() }; for (int i = 0; i < operationCount; i++) { string key = $"TestKey_{i}"; object testData = new object(); long size = 1024; var startTime = Time.realtimeSinceStartup; if (i % 3 == 0) { object data; if (cacheManager.TryGetFromCache(key, out data)) { result.hitCount++; } else { result.missCount++; cacheManager.AddToCache(key, testData, size, "TestObject"); } } else { cacheManager.AddToCache(key, testData, size, "TestObject"); } float accessTime = Time.realtimeSinceStartup - startTime; accessTimes.Add(accessTime); } result.hitRate = operationCount > 0 ? (float)result.hitCount / operationCount : 0; result.avgAccessTime = accessTimes.Count > 0 ? accessTimes.Average() : 0; var cacheStats = cacheManager.GetCacheStats(); return result; } private string FormatBytes(long bytes) { string[] sizes = { "B", "KB", "MB", "GB" }; int order = 0; double len = bytes; while (len >= 1024 && order < sizes.Length - 1) { order++; len = len / 1024; } return $"{len:0.##} {sizes[order]}"; } public string GetCacheSystemInfo() { var info = new System.Text.StringBuilder(); info.AppendLine("=== 自定义缓存策略系统信息 ==="); info.AppendLine($"启用自定义缓存: {enableCustomCaching}"); info.AppendLine($"缓存策略: {cacheStrategy}"); info.AppendLine($"最大缓存大小: {FormatBytes(maxCacheSize)}"); info.AppendLine($"缓存超时: {cacheTimeout}s"); info.AppendLine($"磁盘缓存: {enableDiskCaching}"); info.AppendLine($"内存缓存: {enableMemoryCaching}"); info.AppendLine(); if (cacheManager != null) { info.AppendLine(cacheManager.GetCacheStats()); } return info.ToString(); } public string GetCacheBestPractices() { var practices = new System.Text.StringBuilder(); practices.AppendLine("=== 自定义缓存策略最佳实践 ==="); practices.AppendLine("1. 策略选择:"); practices.AppendLine(" - LRU: 适用于访问模式相对稳定"); practices.AppendLine(" - LFU: 适用于有明显热点数据"); practices.AppendLine(" - FIFO: 适用于数据时效性强"); practices.AppendLine(" - Priority: 适用于有明确优先级"); practices.AppendLine(); practices.AppendLine("2. 大小管理:"); practices.AppendLine(" - 设置合理的缓存大小限制"); practices.AppendLine(" - 实现智能的驱逐策略"); practices.AppendLine(" - 监控缓存命中率"); practices.AppendLine(); practices.AppendLine("3. 性能优化:"); practices.AppendLine(" - 使用高效的数据结构"); practices.AppendLine(" - 实现异步缓存操作"); practices.AppendLine(" - 避免缓存雪崩"); practices.AppendLine(); practices.AppendLine("4. 内存管理:"); practices.AppendLine(" - 及时释放不需要的缓存"); practices.AppendLine(" - 实现内存使用监控"); practices.AppendLine(" - 防止内存泄漏"); practices.AppendLine(); practices.AppendLine("5. 持久化:"); practices.AppendLine(" - 实现磁盘缓存支持"); practices.AppendLine(" - 确保数据一致性"); practices.AppendLine(" - 处理缓存文件损坏"); return practices.ToString(); } void OnDestroy() { Debug.Log("自定义缓存策略系统清理完成"); } }
|