QueueCache.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Module\LCache;
  3. use UCore\Helper\Logger;
  4. use function Laravel\Prompts\select;
  5. trait QueueCache
  6. {
  7. public function run(): bool
  8. {
  9. $indexs = static::getRequiredArgIndex();
  10. foreach ($indexs as $index) {
  11. if (!isset($this->arg[$index])) {
  12. Logger::error("Cache-error", [ $this->arg, $indexs, $index ]);
  13. return false;
  14. }
  15. }
  16. // dump($this->arg);
  17. $key = self::getKey($this->arg);
  18. $key2 = $key . '_PD';// 防止重复执行
  19. $pd = SCache::get($key2);
  20. if ($pd->isHit()) {
  21. // 重复执行
  22. return true;
  23. }
  24. $d = static::getNewData($this->arg);
  25. self::updateData($key, $d);
  26. return true;
  27. }
  28. public static function updateData($key, $d)
  29. {
  30. $key2 = $key . '_PD';// 防止重复执行
  31. // dump($key,$d);
  32. $data = new CacheItem($key, $d, 0, static::getTtl());
  33. SCache::put($key, $data, null);
  34. SCache::put($key2, 1, static::getPreventDuplication());
  35. return $data;
  36. }
  37. /**
  38. * 更新数据,同步,强制
  39. *
  40. * @param $arg
  41. * @return void
  42. */
  43. static public function updateSync($parameter)
  44. {
  45. $key = static::getKey($parameter);
  46. $d = static::getNewData($parameter);
  47. $data = new CacheItem($key, $d, time(), static::getTtl());
  48. SCache::put($key, $data, null);
  49. return $key;
  50. }
  51. /**
  52. * 获取缓存key
  53. *
  54. * @param $parameter
  55. * @return string
  56. */
  57. static protected function getKey($parameter)
  58. {
  59. return md5(serialize([ static::class, $parameter ]));
  60. }
  61. /**
  62. * 获取数据
  63. *
  64. * @return mixed|null
  65. */
  66. static public function getData($parameter = [], $force = false)
  67. {
  68. $key = static::getKey($parameter);
  69. $item = SCache::get($key);
  70. // var_dump($key);
  71. // 3ee2d37c91b4abcf418bd24c0c0e1dea
  72. // 3ee2d37c91b4abcf418bd24c0c0e1dea
  73. if (!$item->isHit()) {
  74. $force = true;
  75. }
  76. if ($force) {
  77. $d = static::getNewData($parameter);
  78. $item = self::updateData($key, $d);
  79. }
  80. return $item->getValue();
  81. }
  82. }