Repository navigation
Expand file tree
/
Copy pathCacheService.php
More file actions
1317 lines (1108 loc) · 44.5 KB
/
Copy pathCacheService.php
File metadata and controls
1317 lines (1108 loc) · 44.5 KB
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace app\service;
use APCUIterator;
use DateInterval;
use DateTimeImmutable;
use Error;
use Exception;
use Memcached;
use support\Log;
use support\Redis;
class CacheService
{
private static $handler = null;
private static bool $fallbackMode = false;
private static int $lastFallbackTime = 0;
private static $failedDrivers = [];
private static string $prefix = '';
/**
* 环境变量缓存
*/
private static array $envCache = [];
/**
* 获取环境变量,带缓存
*
* @param string $key 环境变量键名
* @param mixed $default 默认值
*
* @return mixed 环境变量值
*/
private static function getEnv(string $key, mixed $default = null): mixed
{
if (!isset(self::$envCache[$key])) {
self::$envCache[$key] = getenv($key) ?: $default;
}
return self::$envCache[$key];
}
/**
* 获取缓存处理器
*
* @throws Exception
*/
public static function getHandler()
{
// 从缓存获取环境变量,减少系统调用
$rawDriver = self::getEnv('CACHE_DRIVER', 'null');
$cacheDriver = is_string($rawDriver) ? strtolower(trim($rawDriver)) : '';
if ($cacheDriver === '' || $cacheDriver === 'null' || $cacheDriver === 'none' || $rawDriver === false) {
$cacheDriver = 'none';
} elseif ($cacheDriver === 'array') {
// 将 array 作为 memory 的别名
$cacheDriver = 'memory';
}
// 统一初始化前缀(设置默认前缀以支持模式匹配的缓存清除)
// 只有当前缀为空时才设置,避免重复赋值
if (self::$prefix === '') {
self::$prefix = self::getEnv('CACHE_PREFIX', '');
}
// 如果不是在回退模式,且驱动没有失败,则返回现有处理器
if (
self::$handler !== null && !self::$fallbackMode &&
!(self::$failedDrivers[$cacheDriver] ?? false)
) {
return self::$handler;
}
if (self::$fallbackMode) {
$currentTime = time();
if ($currentTime - self::$lastFallbackTime > 300) {
Log::info('[cache] fallback mode expired, trying to exit fallback mode...');
self::$fallbackMode = false;
self::$failedDrivers = [];
self::$handler = null;
} else {
return self::createNoneHandler();
}
}
$strictMode = filter_var(self::getEnv('CACHE_STRICT_MODE', 'false'), FILTER_VALIDATE_BOOLEAN);
// 显式禁用缓存时直接返回无缓存处理器,避免进入连接测试/回退模式
if ($cacheDriver === 'none') {
self::$handler = self::createNoneHandler();
self::$fallbackMode = false;
return self::$handler;
}
try {
self::$handler = self::createHandler($cacheDriver);
if (!self::testConnection(self::$handler)) {
throw new Exception("Cache driver connection test failed: {$cacheDriver}");
}
self::$fallbackMode = false;
return self::$handler;
} catch (Exception $e) {
Log::error("[cache] exception: {$e->getMessage()}", ['driver' => $cacheDriver]);
if ($strictMode) {
throw $e;
}
self::$failedDrivers[$cacheDriver] = time();
self::$fallbackMode = true;
self::$lastFallbackTime = time();
self::$handler = null;
return self::createNoneHandler();
}
}
/**
* 创建缓存处理器
*/
private static function createHandler($driver)
{
switch ($driver) {
case 'redis':
return new class () {
private $redis;
private $isCluster = false;
public function __construct()
{
$this->redis = Redis::connection('cache');
// 检测是否为集群模式
try {
$info = $this->redis->info('cluster');
$this->isCluster = isset($info['cluster_enabled']) && $info['cluster_enabled'] == 1;
} catch (\Exception $e) {
$this->isCluster = false;
}
}
public function get(string $key)
{
try {
$value = $this->redis->get($key);
return $value === null ? false : $value;
} catch (Exception $e) {
Log::error("[cache] Redis get error: {$e->getMessage()}");
return false;
}
}
public function setex(string $key, int $ttl, string $value): bool
{
try {
return $this->redis->setex($key, $ttl, $value);
} catch (Exception $e) {
Log::error("[cache] Redis setex error: {$e->getMessage()}");
return false;
}
}
public function set(string $key, mixed $value, int $ttl = 0): bool
{
try {
// 序列化非字符串值
$serialized = is_string($value) ? $value : serialize($value);
if ($ttl > 0) {
return $this->redis->setex($key, $ttl, $serialized);
} else {
return $this->redis->set($key, $serialized);
}
} catch (Exception $e) {
Log::error("[cache] Redis set error: {$e->getMessage()}");
return false;
}
}
public function del(string $key): bool
{
try {
return $this->redis->del($key) > 0;
} catch (Exception $e) {
Log::error("[cache] Redis del error: {$e->getMessage()}");
return false;
}
}
public function has(string $key): bool
{
try {
return $this->redis->exists($key) > 0;
} catch (Exception $e) {
Log::error("[cache] Redis has error: {$e->getMessage()}");
return false;
}
}
};
case 'apcu':
if (!extension_loaded('apcu') || !apcu_enabled()) {
throw new Exception('APCu extension is not loaded or not enabled');
}
return new class () {
public function get(string $key)
{
$result = apcu_fetch($key, $success);
return $success ? $result : false;
}
public function setex(string $key, int $ttl, string $value): bool
{
return apcu_store($key, $value, $ttl);
}
public function set(string $key, mixed $value, int $ttl = 0): bool
{
// 序列化非字符串值
$serialized = is_string($value) ? $value : serialize($value);
// ttl=0 表示永久
return apcu_store($key, $serialized, $ttl);
}
public function del(string $key): bool
{
return apcu_delete($key);
}
public function has(string $key): bool
{
return apcu_exists($key);
}
};
case 'memcached':
if (!extension_loaded('memcached')) {
throw new Exception('Memcached extension is not loaded');
}
return new class () {
private $memcached;
public function __construct()
{
$this->memcached = new Memcached();
$this->memcached->addServer(
getenv('MEMCACHED_HOST') ?: '127.0.0.1',
(int) (getenv('MEMCACHED_PORT') ?: 11211)
);
}
public function get(string $key)
{
$result = $this->memcached->get($key);
return $this->memcached->getResultCode() === Memcached::RES_SUCCESS ? $result : false;
}
public function setex(string $key, int $ttl, string $value): bool
{
return $this->memcached->set($key, $value, $ttl);
}
public function set(string $key, mixed $value, int $ttl = 0): bool
{
// 序列化非字符串值
$serialized = is_string($value) ? $value : serialize($value);
// Memcached 的 ttl=0 表示不过期
return $this->memcached->set($key, $serialized, $ttl);
}
public function del(string $key): bool
{
return $this->memcached->delete($key);
}
public function has(string $key): bool
{
$result = $this->memcached->get($key);
return $this->memcached->getResultCode() === Memcached::RES_SUCCESS;
}
};
case 'memory':
// 进程内内存缓存(仅在当前进程有效),支持 TTL
return new class () {
private array $data = [];
public function get(string $key)
{
$now = time();
if (!isset($this->data[$key])) {
return false;
}
$item = $this->data[$key];
if ($item['expire'] !== null && $item['expire'] < $now) {
unset($this->data[$key]);
return false;
}
// 反序列化存储的值
$value = $item['value'];
if (is_string($value) && !is_numeric($value) && $value !== '') {
// 尝试反序列化,如果是序列化数据
$unserialized = @unserialize($value);
if ($unserialized !== false || $value === serialize(false)) {
return $unserialized;
}
}
return $value;
}
public function setex(string $key, int $ttl, string $value): bool
{
$this->data[$key] = [
'value' => $value,
'expire' => $ttl > 0 ? time() + $ttl : null,
];
return true;
}
public function set(string $key, mixed $value, int $ttl = 0): bool
{
// 序列化非字符串值
$serialized = is_string($value) ? $value : serialize($value);
$this->data[$key] = [
'value' => $serialized,
'expire' => $ttl > 0 ? time() + $ttl : null,
];
return true;
}
public function del(string $key): bool
{
$exists = isset($this->data[$key]);
unset($this->data[$key]);
return $exists;
}
public function has(string $key): bool
{
$now = time();
if (!isset($this->data[$key])) {
return false;
}
$item = $this->data[$key];
if ($item['expire'] !== null && $item['expire'] < $now) {
unset($this->data[$key]);
return false;
}
return true;
}
};
case 'none':
return self::createNoneHandler();
default:
throw new Exception("Unsupported cache driver: {$driver}");
}
}
/**
* 创建无缓存处理器
*/
private static function createNoneHandler()
{
return new class () {
public function get(string $key)
{
return false;
}
public function setex(string $key, int $ttl, string $value): bool
{
return true;
}
public function set(string $key, mixed $value, int $ttl = 0): bool
{
return true;
}
public function del(string $key): bool
{
return true;
}
public function has(string $key): bool
{
return false;
}
};
}
/**
* 测试连接
*/
private static function testConnection($handler): bool
{
try {
$testKey = self::prefixKey('__cache_connection_test__');
$testValue = 'test';
// 优先走 setex,失败则尝试 set
$setOk = false;
if (method_exists($handler, 'setex')) {
$setOk = $handler->setex($testKey, 2, $testValue);
}
if (!$setOk && method_exists($handler, 'set')) {
$setOk = $handler->set($testKey, $testValue);
}
if (!$setOk) {
return false;
}
$getResult = $handler->get($testKey);
return $getResult === $testValue;
} catch (Exception $e) {
Log::error("[cache] connection test failed: {$e->getMessage()}");
return false;
}
}
/**
* 验证缓存键
*/
private static function validateCacheKey(string $key): bool
{
if (empty($key)) {
Log::warning('[cache] empty key provided');
return false;
}
return true;
}
/**
* 序列化值
*/
private static function serializeValue(mixed $value, bool $use_igbinary): ?string
{
// 序列化策略:JSON优先,失败回退 igbinary/serialize,并打标前缀
$serialized_value = null;
$serializer = self::getEnv('CACHE_SERIALIZER', 'json');
if ($serializer === 'json') {
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json !== false && $json !== null) {
$serialized_value = 'json:' . $json;
}
}
if ($serialized_value === null && $use_igbinary) {
$bin = igbinary_serialize($value);
if ($bin !== false) {
$serialized_value = 'igb:' . $bin;
}
}
if ($serialized_value === null) {
$ser = serialize($value);
if ($ser !== false) {
$serialized_value = 'ser:' . $ser;
}
}
if ($serialized_value === null) {
Log::error('[cache] failed to serialize value');
}
return $serialized_value;
}
/**
* 计算 TTL
*/
private static function calculateTTL(?int $ttl, mixed $value, bool $isConfigKey): int
{
// 默认TTL + 负缓存TTL + 随机抖动
$default_ttl = (int) self::getEnv('CACHE_DEFAULT_TTL', 86400);
$expire_time = is_numeric($ttl) ? (int) $ttl : $default_ttl;
if ($expire_time < 0) {
$expire_time = $default_ttl;
}
$is_negative = ($value === null) || ($value === '') || (is_array($value) && count($value) === 0);
// blog_config_* 键禁用负缓存
if ($is_negative && !$isConfigKey) {
$neg_ttl = (int) self::getEnv('CACHE_NEGATIVE_TTL', 30);
$expire_time = max(1, $neg_ttl);
}
// 抖动,避免同时过期雪崩
$jitter_sec = (int) self::getEnv('CACHE_JITTER_SECONDS', 0);
if ($jitter_sec > 0 && $expire_time > 1) {
$expire_time += random_int(0, $jitter_sec);
}
return $expire_time;
}
/**
* 处理特殊键
*/
private static function handleSpecialKeys(string $key, mixed $value, $cache_handler, string $cache_driver): ?bool
{
$isConfigKey = str_starts_with($key, 'blog_config_');
$is_negative = ($value === null) || ($value === '') || (is_array($value) && count($value) === 0);
// blog_config_* 空值不缓存:避免将空配置写入缓存导致下游连接失败
if ($isConfigKey && $is_negative) {
try {
// 清理可能存在的旧值(正常键与负缓存键)
$cache_handler->del(self::prefixKey($key));
$cache_handler->del(self::prefixKey($key . '::neg'));
} catch (Exception $e) {
Log::warning('[cache] blog_config skip cache and cleanup warn: ' . $e->getMessage());
}
// 跳过写入缓存,直接返回原值(空),由上层处理重新加载或报错
// 同时释放锁
self::releaseLock($key, $cache_driver);
return true;
}
return false;
}
/**
* 生成存储键
*/
private static function generateStoreKey(string $key, mixed $value, bool $isConfigKey): string
{
$is_negative = ($value === null) || ($value === '') || (is_array($value) && count($value) === 0);
// 设置存储键:负缓存追加 ::neg 后缀(blog_config_* 不使用负缓存)
return self::prefixKey($key . (($is_negative && !$isConfigKey) ? '::neg' : ''));
}
/**
* 释放锁
*/
private static function releaseLock(string $key, string $cache_driver): void
{
try {
$lockKey = self::prefixKey('__cache_lock:' . $key);
if ($cache_driver === 'redis') {
$redis = Redis::connection('cache');
$redis->del($lockKey);
} elseif (function_exists('apcu_delete') && apcu_enabled()) {
apcu_delete($lockKey);
}
} catch (Exception $e) {
Log::warning('[cache] unlock warn: ' . $e->getMessage());
}
}
/**
* 处理负缓存
*/
private static function handleNegativeCache(string $key, $cache_handler): bool
{
$isConfigKey = str_starts_with($key, 'blog_config_');
if (!$isConfigKey) {
$negPrefKey = self::prefixKey($key . '::neg');
$negHit = $cache_handler->get($negPrefKey);
if ($negHit !== false) {
return true;
}
}
return false;
}
/**
* 防止缓存击穿
*/
private static function preventCacheStampede(string $key, string $cache_driver, $cache_handler, &$cached): void
{
$isConfigKey = str_starts_with($key, 'blog_config_');
if ($cached === false) {
// 防缓存击穿:在计算锁存在期间进行可配置的多次退避重试
$busyWaitMs = (int) self::getEnv('CACHE_BUSY_WAIT_MS', 50);
$maxRetries = (int) self::getEnv('CACHE_BUSY_MAX_RETRIES', 3);
$lockTtlMs = (int) self::getEnv('CACHE_LOCK_TTL_MS', 3000);
$lockKey = self::prefixKey('__cache_lock:' . $key);
$prefKey = self::prefixKey($key);
try {
$acquired = false;
if ($cache_driver === 'redis') {
$redis = Redis::connection('cache');
// 尝试设置计算锁,若失败说明已有计算者
// 使用 Lua 脚本以避免 set 方法签名的兼容性问题
// $acquired = (bool) $redis->set($lockKey, '1', ['nx', 'px' => $lockTtlMs]);
$script = "return redis.call('set', KEYS[1], '1', 'NX', 'PX', ARGV[1])";
$result = $redis->eval($script, 1, $lockKey, $lockTtlMs);
$acquired = ($result === true || $result === 'OK' || (is_object($result) && (string) $result === 'OK'));
if (!$acquired) {
for ($i = 0; $i < $maxRetries; $i++) {
usleep(max(0, $busyWaitMs) * 1000);
$cached = $cache_handler->get($prefKey);
if ($cached !== false) {
break;
}
// 再次检查负缓存(blog_config_* 跳过)
if (!$isConfigKey) {
$negHit = $cache_handler->get(self::prefixKey($key . '::neg'));
if ($negHit !== false) {
$cached = false;
break;
}
}
// 简单指数退避,并参考锁剩余时间进行上限控制
$pttl = method_exists($redis, 'pttl') ? $redis->pttl($lockKey) : -1;
if ($pttl > 0) {
$busyWaitMs = min($busyWaitMs * 2, max(50, (int) ($pttl / 2)));
} else {
$busyWaitMs = min($busyWaitMs * 2, 500);
}
}
}
} elseif (function_exists('apcu_add') && apcu_enabled()) {
$acquired = apcu_add($lockKey, 1, (int) ceil($lockTtlMs / 1000));
if (!$acquired) {
for ($i = 0; $i < $maxRetries; $i++) {
usleep(max(0, $busyWaitMs) * 1000);
$cached = $cache_handler->get($prefKey);
if ($cached !== false) {
break;
}
// APCU 路径下同样跳过 blog_config_* 的负缓存短路
if (!$isConfigKey) {
$negHit = $cache_handler->get(self::prefixKey($key . '::neg'));
if ($negHit !== false) {
$cached = false;
break;
}
}
$busyWaitMs = min($busyWaitMs * 2, 500);
}
}
}
} catch (Exception $e) {
Log::warning('[cache] stampede warn: ' . $e->getMessage());
}
}
}
/**
* 解码缓存值
*/
private static function decodeCachedValue(string $key, string $raw, bool $use_igbinary): mixed
{
// 新版标记解码,兼容旧数据
// blog_config_* 空值防护:命中到 json:"" 或 json:null 则视为未命中,并删除问题键
if (str_starts_with($key, 'blog_config_')) {
if ($raw === 'json:""' || $raw === 'json:null') {
try {
$cache_handler = self::getHandler();
$cache_handler->del(self::prefixKey($key));
} catch (Exception $e) {
Log::warning('[cache] blog_config empty value cleanup warn: ' . $e->getMessage());
}
return false;
}
}
if (str_starts_with($raw, 'json:')) {
$decoded = json_decode(substr($raw, 5), true);
return $decoded !== null ? $decoded : substr($raw, 5);
} elseif (str_starts_with($raw, 'igb:')) {
$payload = substr($raw, 4);
if (function_exists('igbinary_unserialize')) {
$unserialized = @igbinary_unserialize($payload);
return $unserialized !== null ? $unserialized : $payload;
} else {
$unserialized = @unserialize($payload);
return $unserialized !== false ? $unserialized : $payload;
}
} elseif (str_starts_with($raw, 'ser:')) {
$payload = substr($raw, 4);
$unserialized = @unserialize($payload);
return $unserialized !== false ? $unserialized : $payload;
} else {
// 兼容旧逻辑
if ($use_igbinary) {
$unserialized = igbinary_unserialize($raw);
if ($unserialized === null && $raw !== igbinary_serialize(null)) {
$unserialized = @unserialize($raw);
return $unserialized !== false ? $unserialized : $raw;
} else {
return $unserialized;
}
} else {
if ($raw !== '' && str_starts_with($raw, "\x00\x00\x00\x02") && function_exists('igbinary_unserialize')) {
$unserialized = @igbinary_unserialize($raw);
if ($unserialized !== null) {
return $unserialized;
}
}
$unserialized = @unserialize($raw);
return $unserialized !== false ? $unserialized : $raw;
}
}
}
/**
* 获取或设置缓存
*/
public static function cache(string $key, mixed $value = null, bool $set = false, ?int $ttl = null): mixed
{
try {
if (!self::validateCacheKey($key)) {
return false;
}
$cache_handler = self::getHandler();
$use_igbinary = extension_loaded('igbinary');
$cache_driver = self::getEnv('CACHE_DRIVER', 'redis');
if ($set) {
$serialized_value = self::serializeValue($value, $use_igbinary);
if ($serialized_value === null) {
return false;
}
$isConfigKey = str_starts_with($key, 'blog_config_');
$expire_time = self::calculateTTL($ttl, $value, $isConfigKey);
// 处理特殊键
if (self::handleSpecialKeys($key, $value, $cache_handler, $cache_driver)) {
return $value;
}
$storeKey = self::generateStoreKey($key, $value, $isConfigKey);
// 统一前缀写入 + 锁释放
if ($expire_time === 0 && method_exists($cache_handler, 'set')) {
$result = $cache_handler->set($storeKey, $serialized_value);
} else {
$cache_ttl = (int) max(1, $expire_time);
$result = $cache_handler->setex($storeKey, $cache_ttl, $serialized_value);
}
if ($result === false) {
Log::error('[cache] failed to set cache key: ' . $storeKey);
return false;
}
// 结束计算,清理锁
self::releaseLock($key, $cache_driver);
return $value;
} else {
$prefKey = self::prefixKey($key);
$cached = $cache_handler->get($prefKey);
if ($cached === false) {
// 处理负缓存
if (self::handleNegativeCache($key, $cache_handler)) {
return false;
}
// 防止缓存击穿
self::preventCacheStampede($key, $cache_driver, $cache_handler, $cached);
if ($cached === false) {
return false;
}
}
// 解码缓存值
return self::decodeCachedValue($key, (string) $cached, $use_igbinary);
}
} catch (Exception $e) {
Log::error('[cache] exception: ' . $e->getMessage());
return null;
} catch (Error $e) {
Log::error('[cache] error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
return null;
}
}
/**
* 验证清除缓存的模式
*
* @param string $pattern 缓存模式
* @param string $logPrefix 日志前缀
*
* @return bool 是否验证通过
*/
private static function validateClearPattern(string $pattern, string $logPrefix): bool
{
// 确保前缀已经初始化
self::prefixKey('');
// 安全保护:当前缀为空且请求清理 '*' 时,需要显式确认
if (self::$prefix === '') {
$allowAll = filter_var(self::getEnv('CACHE_ALLOW_CLEAR_ALL', 'false'), FILTER_VALIDATE_BOOLEAN);
if (!$allowAll) {
Log::warning("[{$logPrefix}] prefix is empty and pattern contains *, refused (set CACHE_ALLOW_CLEAR_ALL=true)");
return false;
}
}
return true;
}
/**
* 清除 Redis 缓存
*
* @param string $patternWithPrefix 带前缀的缓存模式
* @param string $logPrefix 日志前缀
*
* @return bool 是否清除成功
* @throws \Throwable
*/
private static function clearRedisCache(string $patternWithPrefix, string $logPrefix): bool
{
try {
$redis = Redis::connection('cache');
if (!$redis) {
return true;
}
$regex = '/^' . str_replace('*', '.*', preg_quote($patternWithPrefix, '/')) . '$/';
$cursor = 0;
$deleted = 0;
do {
[$cursor, $keys] = $redis->scan($cursor, ['match' => self::$prefix . '*', 'count' => 1000]);
if (is_array($keys) && !empty($keys)) {
$matchKeys = array_values(array_filter($keys, function ($k) use ($regex) {
return preg_match($regex, $k) === 1;
}));
if (!empty($matchKeys)) {
$deleted += $redis->del($matchKeys);
}
}
} while ($cursor !== 0);
return $deleted >= 0;
} catch (Exception $e) {
Log::warning("[{$logPrefix}] Redis clear warn: " . $e->getMessage());
return false;
}
}
/**
* 清除 APCU 缓存
*
* @param string $patternWithPrefix 带前缀的缓存模式
* @param string $logPrefix 日志前缀
*
* @return bool 是否清除成功
*/
private static function clearApcCache(string $patternWithPrefix, string $logPrefix): bool
{
try {
if (!function_exists('apcu_enabled') || !apcu_enabled()) {
return true;
}
$regex = '/^' . str_replace('*', '.*', preg_quote($patternWithPrefix, '/')) . '$/';
$iterator = new APCUIterator($regex, APC_ITER_KEY);
$success = true;
foreach ($iterator as $key => $value) {
if (!apcu_delete($key)) {
$success = false;
}
}
return $success;
} catch (Exception $e) {
Log::warning("[{$logPrefix}] APCU clear warn: " . $e->getMessage());
return false;
}
}
/**
* 清除 Memcached 缓存
*
* @param string $logPrefix 日志前缀
*
* @return bool 是否清除成功
*/
private static function clearMemcachedCache(string $logPrefix): bool
{
try {
if (!extension_loaded('memcached')) {
return true;
}
$memcached = new Memcached();
$memcached->addServer(self::getEnv('MEMCACHED_HOST', '127.0.0.1'), (int) self::getEnv('MEMCACHED_PORT', 11211));
// Memcached不支持模式删除,只能选择flush(风险较大);这里按前缀无法精准删除,选择跳过
Log::warning("[{$logPrefix}] Memcached pattern clearing not supported; consider flush if needed");
return true;
} catch (Exception $e) {
Log::warning("[{$logPrefix}] Memcached clear warn: " . $e->getMessage());
return false;
}
}
/**
* 快速清除缓存
*/
public static function clearCache(string $pattern = '*'): bool
{
try {
$cache_handler = self::getHandler();
if (str_contains($pattern, '*')) {
$cache_driver = self::getEnv('CACHE_DRIVER', 'redis');
$patternWithPrefix = self::$prefix . $pattern;
// 验证清除模式
if (!self::validateClearPattern($pattern, 'clear_cache')) {
return true;
}
switch ($cache_driver) {
case 'redis':
try {
self::clearRedisCache($patternWithPrefix, 'clear_cache');
} catch (Exception $e) {
// Redis清理失败,不产生警告,只记录调试日志
Log::debug('[clear_cache] Redis clear failed: ' . $e->getMessage());
}
return true;
case 'apcu':
try {
self::clearApcCache($patternWithPrefix, 'clear_cache');
} catch (Exception $e) {
// APCU清理失败,不产生警告,只记录调试日志
Log::debug('[clear_cache] APCU clear failed: ' . $e->getMessage());
}
return true;
case 'memcached':
// Memcached不支持模式清除,直接返回true
Log::debug('[clear_cache] Memcached does not support pattern-based cache clearing');
return true;
case 'memory':
// 进程内缓存:当前进程内的键会在后续请求中按需重建
return true;
case 'none':
return true;
default:
// 不支持的驱动,直接返回true,避免产生警告
Log::debug("[clear_cache] Pattern-based clearing not supported for driver: {$cache_driver}");
return true;