缓存

Testing Is Documentation

tests/Cache/CacheTest.php缓存 - 图1

QueryPHP 为系统提供了灵活的缓存功能,提供了多种缓存驱动。

内置支持的缓存类型包括 file、redis,未来可能增加其他驱动。

使用方式

使用容器 caches 服务

  1. \App::make('caches')->set(string $name, $data, ?int $expire = null): void;
  2. \App::make('caches')->get(string $name, $defaults = false, ?int $expire = null);

依赖注入

  1. class Demo
  2. {
  3. private \Leevel\Cache\Manager $cache;
  4. public function __construct(\Leevel\Cache\Manager $cache)
  5. {
  6. $this->cache = $cache;
  7. }
  8. }

使用静态代理

  1. \Leevel\Cache\Proxy\Cache::set(string $name, $data, ?int $expire = null): void;
  2. \Leevel\Cache\Proxy\Cache::get(string $name, $defaults = false, ?int $expire = null);

缓存配置

系统的缓存配置位于应用下面的 option/cache.php 文件。

可以定义多个缓存连接,并且支持切换,每一个连接支持驱动设置。

  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the your app package.
  5. *
  6. * The PHP Application For Code Poem For You.
  7. * (c) 2018-2099 http://yourdomian.com All rights reserved.
  8. *
  9. * For the full copyright and license information, please view the LICENSE
  10. * file that was distributed with this source code.
  11. */
  12. return [
  13. /*
  14. * ---------------------------------------------------------------
  15. * 默认缓存驱动
  16. * ---------------------------------------------------------------
  17. *
  18. * 这里可以可以设置为 file、memcache 等
  19. * 系统为所有缓存提供了统一的接口,在使用上拥有一致性
  20. */
  21. 'default' => Leevel::env('CACHE_DRIVER', 'file'),
  22. /*
  23. * ---------------------------------------------------------------
  24. * 程序默认缓存时间
  25. * ---------------------------------------------------------------
  26. *
  27. * 设置好缓存时间,超过这个时间系统缓存会重新进行获取, 小与等于 0 表示永不过期
  28. * 缓存时间为当前时间加上以秒为单位的数量
  29. */
  30. 'expire' => (int) Leevel::env('CACHE_EXPIRE', 86400),
  31. /*
  32. * ---------------------------------------------------------------
  33. * 缓存时间预置
  34. * ---------------------------------------------------------------
  35. *
  36. * 为了满足不同的需求,有部分缓存键值需要的缓存时间不一致,有些缓存可能需要频繁更新
  37. * 于是这里我们可以通过配置缓存预设时间来控制缓存的键值的特殊时间,其中 * 表示通配符
  38. * 键值 = 缓存值,键值不带前缀,例如 ['option' => 60]
  39. */
  40. 'time_preset' => [],
  41. /*
  42. * ---------------------------------------------------------------
  43. * 缓存连接参数
  44. * ---------------------------------------------------------------
  45. *
  46. * 这里为所有的缓存的连接参数,每一种不同的驱动拥有不同的配置
  47. * 虽然有不同的驱动,但是在缓存使用上却有着一致性
  48. */
  49. 'connect' => [
  50. 'file' => [
  51. // driver
  52. 'driver' => 'file',
  53. // 文件缓存路径
  54. 'path' => Leevel::runtimePath('file'),
  55. // 默认过期时间
  56. 'expire' => null,
  57. ],
  58. 'redis' => [
  59. // driver
  60. 'driver' => 'redis',
  61. // 默认缓存服务器
  62. 'host' => Leevel::env('CACHE_REDIS_HOST', '127.0.0.1'),
  63. // 默认缓存服务器端口
  64. 'port' => (int) Leevel::env('CACHE_REDIS_PORT', 6379),
  65. // 认证密码
  66. 'password' => Leevel::env('CACHE_REDIS_PASSWORD', ''),
  67. // redis 数据库索引
  68. 'select' => 0,
  69. // 超时设置
  70. 'timeout' => 0,
  71. // 是否使用持久连接
  72. 'persistent' => false,
  73. // 默认过期时间
  74. 'expire' => null,
  75. ],
  76. 'redisPool' => [
  77. // driver
  78. 'driver' => 'redisPool',
  79. // redis 连接
  80. 'redis_connect' => 'redis',
  81. // 最小空闲连接池数据量
  82. 'max_idle_connections' => (int) Leevel::env('CACHE_REDIS_POOL_MAX_IDLE_CONNECTIONS', 30),
  83. // 最大空闲连接池数据量
  84. 'min_idle_connections' => (int) Leevel::env('CACHE_REDIS_POOL_MIN_IDLE_CONNECTIONS', 10),
  85. // 通道写入最大超时时间设置(单位为毫秒)
  86. 'max_push_timeout' => -1000,
  87. // 通道获取最大等待超时(单位为毫秒)
  88. 'max_pop_timeout' => 0,
  89. // 连接的存活时间(单位为毫秒)
  90. 'keep_alive_duration' => 60000,
  91. // 最大尝试次数
  92. 'retry_times' => 3,
  93. ],
  94. 'file_throttler' => [
  95. // driver
  96. 'driver' => 'file',
  97. // 文件缓存路径
  98. 'path' => Leevel::runtimePath('throttler'),
  99. // 默认过期时间
  100. 'expire' => null,
  101. ],
  102. 'redis_throttler' => [
  103. // driver
  104. 'driver' => 'redis',
  105. // 默认缓存服务器
  106. 'host' => Leevel::env('THROTTLER_REDIS_HOST', '127.0.0.1'),
  107. // 默认缓存服务器端口
  108. 'port' => (int) Leevel::env('THROTTLER_REDIS_PORT', 6379),
  109. // 认证密码
  110. 'password' => Leevel::env('THROTTLER_REDIS_PASSWORD', ''),
  111. // redis 数据库索引
  112. 'select' => 0,
  113. // 超时设置
  114. 'timeout' => 0,
  115. // 是否使用持久连接
  116. 'persistent' => false,
  117. // 默认过期时间
  118. 'expire' => null,
  119. ],
  120. 'file_session' => [
  121. // driver
  122. 'driver' => 'file',
  123. // 文件缓存路径
  124. 'path' => Leevel::runtimePath('session'),
  125. // 默认过期时间
  126. 'expire' => null,
  127. ],
  128. 'redis_session' => [
  129. // driver
  130. 'driver' => 'redis',
  131. // 默认缓存服务器
  132. 'host' => Leevel::env('SESSION_REDIS_HOST', '127.0.0.1'),
  133. // 默认缓存服务器端口
  134. 'port' => (int) Leevel::env('SESSION_REDIS_PORT', 6379),
  135. // 认证密码
  136. 'password' => Leevel::env('SESSION_REDIS_PASSWORD', ''),
  137. // redis 数据库索引
  138. 'select' => 0,
  139. // 超时设置
  140. 'timeout' => 0,
  141. // 是否使用持久连接
  142. 'persistent' => false,
  143. // 默认过期时间
  144. 'expire' => null,
  145. ],
  146. ],
  147. ];

缓存参数根据不同的连接会有所区别,通用的缓存参数如下:

配置项配置描述
expire设置好缓存时间(小与等于 0 表示永不过期,单位时间为秒)
time_preset缓存时间预置

Uses

  1. <?php
  2. use Leevel\Cache\File;
  3. use Leevel\Filesystem\Helper;

缓存基本使用

设置缓存

  1. # Leevel\Cache\ICache::set
  2. /**
  3. * 设置缓存.
  4. *
  5. * @param mixed $data
  6. */
  7. public function set(string $name, $data, ?int $expire = null): void;

缓存配置 $option 根据不同缓存驱动支持不同的一些配置。

file 驱动

配置项配置描述
expire设置好缓存时间(小与等于 0 表示永不过期,单位时间为秒)
time_preset缓存时间预置
path缓存路径

redis 驱动

配置项配置描述
expire设置好缓存时间(小与等于 0 表示永不过期,单位时间为秒)
time_preset缓存时间预置

获取缓存

  1. # Leevel\Cache\ICache::get
  2. /**
  3. * 获取缓存.
  4. *
  5. * @param mixed $defaults
  6. *
  7. * @return mixed
  8. */
  9. public function get(string $name, $defaults = false);

缓存不存在或者过期返回 false,可以根据这个判断缓存是否可用。

删除缓存

  1. # Leevel\Cache\ICache::delete
  2. /**
  3. * 清除缓存.
  4. */
  5. public function delete(string $name): void;

直接指定缓存 key 即可,无返回。

  1. public function testBaseUse(): void
  2. {
  3. $filePath = __DIR__.'/cache/hello.php';
  4. $cache = new File([
  5. 'path' => __DIR__.'/cache',
  6. ]);
  7. $cache->set('hello', 'world');
  8. $this->assertTrue(is_file($filePath));
  9. $this->assertSame('world', $cache->get('hello'));
  10. $cache->delete('hello');
  11. $this->assertFalse(is_file($filePath));
  12. $this->assertFalse($cache->get('hello'));
  13. }

put 批量设置缓存

函数签名

  1. # Leevel\Cache\ICache::put
  2. /**
  3. * 批量设置缓存.
  4. *
  5. * @param array|string $keys
  6. * @param mixed $value
  7. */
  8. public function put($keys, $value = null, ?int $expire = null): void;

TIP

缓存配置 $expireset 的用法一致。

  1. public function testPut(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $cache->put('hello', 'world');
  7. $cache->put(['hello2' => 'world', 'foo' => 'bar']);
  8. $this->assertSame('world', $cache->get('hello'));
  9. $this->assertSame('world', $cache->get('hello2'));
  10. $this->assertSame('bar', $cache->get('foo'));
  11. $cache->delete('hello');
  12. $cache->delete('hello2');
  13. $cache->delete('foo');
  14. $this->assertFalse($cache->get('hello'));
  15. $this->assertFalse($cache->get('hello2'));
  16. $this->assertFalse($cache->get('foo'));
  17. }

set 值 false 不允许作为缓存值

因为 false 会作为判断缓存是否存在的一个依据,所以 false 不能够作为缓存,否则会引起缓存穿透。

  1. public function testSetNotAllowedFalse(): void
  2. {
  3. $this->expectException(\InvalidArgumentException::class);
  4. $this->expectExceptionMessage(
  5. 'Data `false` not allowed to avoid cache penetration.'
  6. );
  7. $cache = new File([
  8. 'path' => __DIR__.'/cache',
  9. ]);
  10. $cache->set('hello', false);
  11. }

put 批量设置缓存支持过期时间

  1. public function testPutWithExpire(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/hello.php';
  7. $cache->put('hello', 'world', 33);
  8. $cache->put(['hello2' => 'world', 'foo' => 'bar'], 22);
  9. $this->assertSame('world', $cache->get('hello'));
  10. $this->assertSame('world', $cache->get('hello2'));
  11. $this->assertSame('bar', $cache->get('foo'));
  12. $this->assertTrue(is_file($filePath));
  13. $this->assertStringContainsString('[33,', file_get_contents($filePath));
  14. $cache->delete('hello');
  15. $cache->delete('hello2');
  16. $cache->delete('foo');
  17. $this->assertFalse($cache->get('hello'));
  18. $this->assertFalse($cache->get('hello2'));
  19. $this->assertFalse($cache->get('foo'));
  20. }

remember 缓存存在读取否则重新设置

缓存值为闭包返回,闭包的参数为缓存的 key

函数签名

  1. # Leevel\Cache\ICache::remember
  2. /**
  3. * 缓存存在读取否则重新设置.
  4. *
  5. * @return mixed
  6. */
  7. public function remember(string $name, Closure $dataGenerator, ?int $expire = null);

TIP

缓存配置 $expireset 的用法一致。

  1. public function testRemember(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/hello.php';
  7. $this->assertFalse(is_file($filePath));
  8. $this->assertSame(['hello' => 'world'], $cache->remember('hello', function (string $key) {
  9. return [$key => 'world'];
  10. }));
  11. $this->assertTrue(is_file($filePath));
  12. $this->assertSame(['hello' => 'world'], $cache->get('hello'));
  13. $cache->delete('hello');
  14. $this->assertFalse($cache->get('hello'));
  15. $this->assertFalse(is_file($filePath));
  16. }

remember 缓存存在读取否则重新设置支持过期时间

  1. public function testRememberWithExpire(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/hello.php';
  7. if (is_file($filePath)) {
  8. unlink($filePath);
  9. }
  10. $this->assertFalse(is_file($filePath));
  11. $this->assertSame('123456', $cache->remember('hello', function (string $key) {
  12. return '123456';
  13. }, 33));
  14. $this->assertTrue(is_file($filePath));
  15. $this->assertSame('123456', $cache->remember('hello', function (string $key) {
  16. return '123456';
  17. }, 4));
  18. $this->assertSame('123456', $cache->get('hello'));
  19. $cache->delete('hello');
  20. $this->assertFalse($cache->get('hello'));
  21. $this->assertFalse(is_file($filePath));
  22. }

has 缓存是否存在

  1. public function testHas(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/has.php';
  7. $this->assertFalse($cache->has('has'));
  8. $cache->set('has', 'world');
  9. $this->assertTrue(is_file($filePath));
  10. $this->assertTrue($cache->has('has'));
  11. }

increase 自增

  1. public function testIncrease(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/increase.php';
  7. $this->assertSame(1, $cache->increase('increase'));
  8. $this->assertTrue(is_file($filePath));
  9. $this->assertSame(101, $cache->increase('increase', 100));
  10. }

decrease 自减

  1. public function testDecrease(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/decrease.php';
  7. $this->assertSame(-1, $cache->decrease('decrease'));
  8. $this->assertTrue(is_file($filePath));
  9. $this->assertSame(-101, $cache->decrease('decrease', 100));
  10. }

ttl 获取缓存剩余时间

剩余时间存在 3 种情况。

  • 不存在的 key:-2
  • key 存在,但没有设置剩余生存时间:-1
  • 有剩余生存时间的 key:剩余时间
  1. public function testTtl(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $filePath = __DIR__.'/cache/ttl.php';
  7. $this->assertFalse($cache->has('ttl'));
  8. $this->assertSame(-2, $cache->ttl('ttl'));
  9. $cache->set('ttl', 'world');
  10. $this->assertTrue(is_file($filePath));
  11. $this->assertSame(86400, $cache->ttl('ttl'));
  12. $cache->set('ttl', 'world', 1);
  13. $this->assertSame(1, $cache->ttl('ttl'));
  14. $cache->set('ttl', 'world', 0);
  15. $this->assertSame(-1, $cache->ttl('ttl'));
  16. }

缓存时间预置

不同场景下面的缓存可能支持不同的时间,我们可以在配置中预设时间而不是在使用时通过第三个参数传递 expire 过期时间,这种做法非常灵活。

缓存时间预设支持 * 通配符,可以灵活控制一类缓存时间。

  1. public function testCacheTime(): void
  2. {
  3. $file = new File([
  4. 'time_preset' => [
  5. 'foo' => 500,
  6. 'bar' => -10,
  7. 'hello*world' => 10,
  8. 'foo*bar' => -10,
  9. ],
  10. 'path' => __DIR__.'/cache',
  11. ]);
  12. $file->set('foo', 'bar');
  13. $file->set('bar', 'hello');
  14. $file->set('hello123456world', 'helloworld1');
  15. $file->set('hello789world', 'helloworld2');
  16. $file->set('foo123456bar', 'foobar1');
  17. $file->set('foo789bar', 'foobar2');
  18. $file->set('haha', 'what about others?');
  19. $this->assertSame('bar', $file->get('foo'));
  20. $this->assertSame('hello', $file->get('bar'));
  21. $this->assertSame('helloworld1', $file->get('hello123456world'));
  22. $this->assertSame('helloworld2', $file->get('hello789world'));
  23. $this->assertSame('foobar1', $file->get('foo123456bar'));
  24. $this->assertSame('foobar2', $file->get('foo789bar'));
  25. $this->assertSame('what about others?', $file->get('haha'));
  26. $file->delete('foo');
  27. $file->delete('bar');
  28. $file->delete('hello123456world');
  29. $file->delete('hello789world');
  30. $file->delete('foo123456bar');
  31. $file->delete('foo789bar');
  32. $file->delete('haha');
  33. }

TIP

缓存时间预设小与等于 0 表示永不过期,单位时间为秒。

键值命名规范

缓存键值默认支持正则 /^[A-Za-z0-9\-\_:.]+$/,可以通过 setKeyRegex 修改。

  1. public function testInvalidCacheKey(): void
  2. {
  3. $this->expectException(\InvalidArgumentException::class);
  4. $this->expectExceptionMessage('Cache key must be `/^[A-Za-z0-9\-\_:.]+$/`.');
  5. $cache = new File([
  6. 'path' => __DIR__.'/cache',
  7. ]);
  8. $cache->set('hello+world', 1);
  9. }

setKeyRegex 设置缓存键值正则

缓存键值默认支持正则 /^[A-Za-z0-9\-\_:.]+$/,可以通过 setKeyRegex 修改。

  1. public function testSetKeyRegex(): void
  2. {
  3. $cache = new File([
  4. 'path' => __DIR__.'/cache',
  5. ]);
  6. $cache->setKeyRegex('/^[a-z+]+$/');
  7. $cache->set('hello+world', 1);
  8. $this->assertSame(1, $cache->get('hello+world'));
  9. }