QueueCache.php 2.0 KB

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