CacheLogTraitModel.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Mead
  5. * Date: 2019/9/4
  6. * Time: 9:36 AM
  7. */
  8. namespace App\Servers\Weikemu\Models;
  9. use App\Maps\CacheMap;
  10. trait CacheLogTraitModel
  11. {
  12. public function cacheLog($box_no, $message_id, $data)
  13. {
  14. $value = '';
  15. if (is_array($data)) {
  16. $value = "array||" . json_encode($data);
  17. } elseif (is_bool($data)) {
  18. $value = "bool||" . ($data ? 1 : 0);
  19. } else {
  20. $value = "string||" . $data;
  21. }
  22. $this->redis->setex(CacheMap::cache_key . ':' . $box_no . ':' . $message_id, 1 * 60, $value);
  23. }
  24. public function getCache($message_id)
  25. {
  26. $val = $this->redis->get(CacheMap::cache_key . ':' . $message_id);
  27. $array = explode(' || ', $val);
  28. if (count($array) !== 2) return false;
  29. list($type, $data) = $array;
  30. switch ($type) {
  31. case 'string':
  32. return $data;
  33. break;
  34. case 'bool':
  35. return (boolean)$data;
  36. break;
  37. case 'array':
  38. return json_decode($data);
  39. }
  40. return false;
  41. }
  42. public function cacheJsonLog($key, $data, $time = 300)
  43. {
  44. $value = json_encode($data, true);
  45. $this->redis->setex(CacheMap::cache_key . ':' . $key, $time, $value);
  46. }
  47. public function getJsonCache($key)
  48. {
  49. $val = $this->redis->get(CacheMap::cache_key . ':' . $key);
  50. return json_decode($val, true);
  51. }
  52. }