CacheAheadAspect.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Cache\Aspect;
  12. use Hyperf\Cache\Annotation\CacheAhead;
  13. use Hyperf\Cache\AnnotationManager;
  14. use Hyperf\Cache\CacheManager;
  15. use Hyperf\Cache\Driver\KeyCollectorInterface;
  16. use Hyperf\Coroutine\Coroutine;
  17. use Hyperf\Di\Aop\AbstractAspect;
  18. use Hyperf\Di\Aop\ProceedingJoinPoint;
  19. class CacheAheadAspect extends AbstractAspect
  20. {
  21. public array $classes = [];
  22. public array $annotations = [
  23. CacheAhead::class,
  24. ];
  25. public function __construct(protected CacheManager $manager, protected AnnotationManager $annotationManager)
  26. {
  27. }
  28. public function process(ProceedingJoinPoint $proceedingJoinPoint)
  29. {
  30. $className = $proceedingJoinPoint->className;
  31. $method = $proceedingJoinPoint->methodName;
  32. $arguments = $proceedingJoinPoint->arguments['keys'];
  33. $now = time();
  34. [$key, $ttl, $group, $annotation] = $this->annotationManager->getCacheAheadValue($className, $method, $arguments);
  35. $driver = $this->manager->getDriver($group);
  36. $callback = static function () use ($proceedingJoinPoint, $driver, $annotation, $key, $now, $ttl) {
  37. $result = $proceedingJoinPoint->process();
  38. if (! in_array($result, (array) $annotation->skipCacheResults, true)) {
  39. $driver->set(
  40. $key,
  41. [
  42. 'expired_time' => $now + $annotation->ttl - $annotation->aheadSeconds,
  43. 'data' => $result,
  44. ],
  45. $ttl
  46. );
  47. if ($driver instanceof KeyCollectorInterface && $annotation instanceof CacheAhead && $annotation->collect) {
  48. $driver->addKey($annotation->prefix . 'MEMBERS', $key);
  49. }
  50. }
  51. return $result;
  52. };
  53. [$has, $result] = $driver->fetch($key);
  54. // If the cache exists, return it directly.
  55. if ($has && isset($result['expired_time'], $result['data'])) {
  56. if (
  57. $now > $result['expired_time']
  58. && $driver->getConnection()->set($key . ':lock', '1', ['NX', 'EX' => $annotation->lockSeconds])
  59. ) { // If the cache is about to expire, refresh the cache.
  60. Coroutine::create($callback);
  61. }
  62. return $result['data'];
  63. }
  64. // If the cache does not exist, execute the callback and cache the result.
  65. return $callback();
  66. }
  67. }