RedisCache.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. namespace App\Services;
  3. use Closure;
  4. use DateInterval;
  5. use DateTimeInterface;
  6. use Illuminate\Support\InteractsWithTime;
  7. use RedisCluster;
  8. /**
  9. * 直接操作 Redis 的缓存,取代 Laravel 原生 Cache。
  10. *
  11. * 前身是 api-v8 的 App\Tools\RedisClusters。接口与 Laravel 的 Cache 门面对齐
  12. * (方法名、参数、返回值、null 与 TTL 语义一致),但只实现 api-v13 真正用到的
  13. * get / put / remember / has / forget / increment 六个;tags、flush 这类在
  14. * Redis Cluster 上跨 slot 或会清空整个集群的操作故意不提供。
  15. *
  16. * 连的是 Redis Cluster,不走 Laravel 的 Redis 门面,用 phpredis 的 RedisCluster 手写连接
  17. * (https://github.com/phpredis/phpredis/blob/develop/cluster.md):
  18. * - 连接:config('mint.redis_cluster.host') : config('mint.redis_cluster.port') 作为种子节点,
  19. * 其余节点由 phpredis 从集群拓扑自动发现;首次读写时才建连
  20. * - key:config('mint.redis_cluster.prefix') . '/' . $key($key 已以 / 开头就不再加),
  21. * 不再叠加 REDIS_PREFIX / CACHE_PREFIX。所以 `foo` 与 `/foo` 是同一个 key
  22. * - 值:JSON。读回来对象一律是关联数组,数字是 int / float(不再是数字字符串);
  23. * 整数编码后就是纯文本数字,ai-translate 用 int() 直接读 `/task/{id}/pointer` 不受影响。
  24. * 存不了 JSON 的值(非 UTF-8 字符串、INF/NAN)写入时抛 JsonException
  25. *
  26. * 集群与 Laravel Cache 用的单机 Redis 不是同一个库,旧缓存不迁移,切换后冷启动。
  27. *
  28. * 二进制(导出的 zip、epub 等)走另一组方法 putBinary / getBinary / binaryLength / getBinaryRange:
  29. * 原样存字节,不经 JSON。同一个 key 只能用一组方法读写——用 get() 读二进制 key 会抛 JsonException,
  30. * 所以二进制 key 要放在自己的命名空间下(如 `/tipitaka-export/file/…`)。大文件用 getBinaryRange
  31. * 分块读(GETRANGE),不必把整个值读进 PHP 内存,也正好支持 HTTP Range。
  32. * 2026-11-21 在 3 主 3 从集群上实测 40MB:SET 95ms、GET 76ms、1MB×40 次 GETRANGE 共 74ms,字节完整。
  33. *
  34. * 业务代码通过门面 App\Facades\RedisCache 调用;测试用 RedisCache::fake()
  35. * 换成内存实现(见 RedisCacheFake)。
  36. */
  37. class RedisCache
  38. {
  39. use InteractsWithTime;
  40. /**
  41. * 调用方没给 TTL(或传 null)时的默认过期秒数:30 天。不提供永久保存。
  42. */
  43. public static int $defaultTtl = 30 * 24 * 60 * 60;
  44. /** @var list<string> 种子节点,形如 `host:port` */
  45. protected array $seeds;
  46. protected string $prefix;
  47. protected ?RedisCluster $client = null;
  48. /**
  49. * @param list<string>|null $seeds
  50. */
  51. public function __construct(?array $seeds = null, ?string $prefix = null)
  52. {
  53. $this->seeds = $seeds ?? [config('mint.redis_cluster.host').':'.config('mint.redis_cluster.port')];
  54. $this->prefix = $prefix ?? (string) config('mint.redis_cluster.prefix', '');
  55. }
  56. /**
  57. * 读取;不存在时返回 $default(可以是闭包)。
  58. */
  59. public function get(string $key, mixed $default = null): mixed
  60. {
  61. $value = $this->read($this->key($key));
  62. return $value === null ? value($default) : $this->unserialize($value);
  63. }
  64. /**
  65. * 写入。$ttl 为 null 时用 static::$defaultTtl;算出来的秒数 <= 0 时等同 forget()。
  66. */
  67. public function put(string $key, mixed $value, DateTimeInterface|DateInterval|int|null $ttl = null): bool
  68. {
  69. $seconds = $this->secondsUntil($ttl ?? static::$defaultTtl);
  70. if ($seconds <= 0) {
  71. return $this->forget($key);
  72. }
  73. return $this->write($this->key($key), $this->serialize($value), $seconds);
  74. }
  75. /**
  76. * 命中就返回缓存,否则执行 $callback 并写入。
  77. *
  78. * 与 Laravel 一致:缓存值为 null 视同未命中,下次会重新计算。
  79. */
  80. public function remember(string $key, DateTimeInterface|DateInterval|int|null $ttl, Closure $callback): mixed
  81. {
  82. $value = $this->get($key);
  83. if ($value !== null) {
  84. return $value;
  85. }
  86. $value = $callback();
  87. $this->put($key, $value, $ttl);
  88. return $value;
  89. }
  90. /**
  91. * 与 Laravel 一致:值为 null 视同不存在。
  92. */
  93. public function has(string $key): bool
  94. {
  95. return $this->get($key) !== null;
  96. }
  97. public function forget(string $key): bool
  98. {
  99. return $this->delete($this->key($key));
  100. }
  101. /**
  102. * 原子自增(INCRBY),返回自增后的值。key 不存在时从 0 开始,且不带过期时间
  103. * (不套用 $defaultTtl:版本号 key 靠它永久递增,过期归零会让旧缓存重新命中)。
  104. */
  105. public function increment(string $key, int $value = 1): int
  106. {
  107. return $this->incrementBy($this->key($key), $value);
  108. }
  109. /**
  110. * 原样写入字节(不经 JSON)。TTL 语义同 put()。
  111. */
  112. public function putBinary(string $key, string $bytes, DateTimeInterface|DateInterval|int|null $ttl = null): bool
  113. {
  114. $seconds = $this->secondsUntil($ttl ?? static::$defaultTtl);
  115. if ($seconds <= 0) {
  116. return $this->forget($key);
  117. }
  118. return $this->write($this->key($key), $bytes, $seconds);
  119. }
  120. /**
  121. * 原样读回 putBinary() 写入的字节;不存在返回 null。
  122. */
  123. public function getBinary(string $key): ?string
  124. {
  125. return $this->read($this->key($key));
  126. }
  127. /**
  128. * 值的字节数(STRLEN);不存在返回 null。
  129. */
  130. public function binaryLength(string $key): ?int
  131. {
  132. return $this->length($this->key($key));
  133. }
  134. /**
  135. * 读字节闭区间 [$start, $end](GETRANGE),越界部分截掉;不存在返回空串。
  136. */
  137. public function getBinaryRange(string $key, int $start, int $end): string
  138. {
  139. return $this->range($this->key($key), $start, $end);
  140. }
  141. /**
  142. * 前缀与 key 之间用 / 隔开:`dev` + `foo` → `dev/foo`;`/task/1` 本身带 /,得 `dev/task/1`。
  143. */
  144. protected function key(string $key): string
  145. {
  146. return $this->prefix.(str_starts_with($key, '/') ? $key : '/'.$key);
  147. }
  148. /**
  149. * 以下六个是仅有的 Redis 存取原语,RedisCacheFake 只需覆盖它们。
  150. * 参数 $key 已带前缀。
  151. */
  152. protected function read(string $key): ?string
  153. {
  154. $value = $this->redis()->get($key);
  155. return $value === false ? null : $value;
  156. }
  157. /**
  158. * 一律用一条 `SET key value EX seconds`:写值与设过期原子完成。
  159. * phpredis 的写法是 `set($key, $value, ['EX' => $seconds])`,不是 Laravel 的 `'EX', $seconds`。
  160. * 不要拆成 SET + EXPIRE(api-v8 的写法)——两条之间出错会留下永不过期的 key。
  161. */
  162. protected function write(string $key, string $value, int $seconds): bool
  163. {
  164. return (bool) $this->redis()->set($key, $value, ['EX' => $seconds]);
  165. }
  166. protected function delete(string $key): bool
  167. {
  168. return (bool) $this->redis()->del($key);
  169. }
  170. protected function incrementBy(string $key, int $value): int
  171. {
  172. return (int) $this->redis()->incrby($key, $value);
  173. }
  174. /**
  175. * STRLEN 对不存在的 key 返回 0,与空值分不清,所以先看 EXISTS。
  176. */
  177. protected function length(string $key): ?int
  178. {
  179. if (! $this->redis()->exists($key)) {
  180. return null;
  181. }
  182. return (int) $this->redis()->strlen($key);
  183. }
  184. protected function range(string $key, int $start, int $end): string
  185. {
  186. $value = $this->redis()->getRange($key, $start, $end);
  187. return is_string($value) ? $value : '';
  188. }
  189. /**
  190. * 第一个参数 null 表示不读 php.ini 里的具名集群,直接用种子节点。
  191. */
  192. protected function redis(): RedisCluster
  193. {
  194. return $this->client ??= new RedisCluster(null, $this->seeds);
  195. }
  196. /**
  197. * 不转义中文与斜杠,省空间也方便在 redis-cli 里直接看;1.0 保持为 1.0,读回来仍是 float。
  198. */
  199. protected function serialize(mixed $value): string
  200. {
  201. return json_encode(
  202. $value,
  203. JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR,
  204. );
  205. }
  206. protected function unserialize(string $value): mixed
  207. {
  208. return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
  209. }
  210. }