├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── src ├── Cache.php ├── Config │ ├── FileConfig.php │ └── SwooleTableConfig.php ├── Drivers │ ├── AbstractDriver.php │ ├── File.php │ ├── Memcache.php │ ├── Redis.php │ └── SwooleTable.php └── Exception │ ├── CacheException.php │ └── InvalidArgumentException.php └── tests ├── FileDriverTest.php ├── MemcachedDriverTest.php ├── RedisDriverTest.php └── SwooleTableDriverTest.php /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /vendor/ 3 | /composer.lock -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Coroutine Cache 2 | ====== 3 | 4 | [![StyleCI](https://styleci.io/repos/110963506/shield?style=flat&branch=master)](https://styleci.io/repos/110963506) 5 | [![Latest Stable Version](https://poser.pugx.org/easyswoole/cache/version)](https://packagist.org/packages/easyswoole/cache) 6 | [![Total Downloads](https://poser.pugx.org/easyswoole/cache/downloads)](https://packagist.org/packages/easyswoole/cache) 7 | [![Latest Unstable Version](https://poser.pugx.org/easyswoole/cache/v/unstable)](//packagist.org/packages/easyswoole/cache) 8 | [![License](https://poser.pugx.org/easyswoole/cache/license)](https://packagist.org/packages/easyswoole/cache) 9 | 10 | 一个轻量级(PSR-16规范)的缓存实现,目前已支持 File Redis Memcached SwooleTable 四种储存模式 11 | 12 | ### 安装 13 | 14 | > composer require easyswoole/cache 15 | 16 | ### 快速开始 17 | 18 | 支持开箱即用的快速缓存,默认使用File驱动,该驱动可以通用协程与非协程模式,所有内置驱动均以PSR16规范实现,静态调用时默认均为调用default驱动,当没有手动注册default驱动时,默认的default驱动为File驱动 19 | 20 | ```php 21 | 22 | use EasySwoole\Cache\Cache; 23 | 24 | $ttl = 10; // 单位秒 25 | $cacheKey = 'cacheKey'; 26 | $cacheValue = 'cacheValue'; 27 | $defaultValue = 'defaultValue'; 28 | 29 | Cache::clear(); 30 | Cache::has($cacheKey); 31 | Cache::delete($cacheKey); 32 | Cache::set($cacheKey, $cacheValue, $ttl); 33 | Cache::get($cacheKey, $defaultValue); 34 | Cache::setMultiple(['CacheKey1' => 'CacheValue1',], $ttl); 35 | Cache::getMultiple(['CacheKey1'], $defaultValue); 36 | Cache::deleteMultiple(['CacheKey1']); 37 | 38 | ``` 39 | 40 | ### 注册驱动 41 | 42 | 系统提供了四种默认驱动,除文件驱动可以在非Swoole环境使用,其他驱动因使用了Sw相关特性或客户端实现,必须在Swoole环境下使用 43 | 44 | ### 文件驱动 45 | 46 | 文件驱动是最洒脱(无任何依赖通杀所有环节)的驱动,性能较其他驱动相对来说比较低,这里演示文件驱动的注册方法,其他驱动的注册方法一致,只是配置项上会有区别 47 | 48 | ```php 49 | 50 | // 请注意先Use要使用的驱动类和配置类 51 | use EasySwoole\Cache\Config\FileConfig; 52 | use EasySwoole\Cache\Drivers\File as FileDriver; 53 | 54 | // 也可以不传入Config 自动使用下面的默认值 55 | $fileDriver = new FileDriver((new FileConfig([ 56 | 'cachePath' => sys_get_temp_dir(), // 缓存目录(默认为PHP系统缓存) 57 | 'cachePrefix' => null, // 默认的缓存前缀 不同前缀分目录存放 58 | 'defaultExpire' => 0, // 默认过期时间 设置为0永不过期 59 | ]))); 60 | 61 | // 注册驱动时不指定驱动名称,则为注册default驱动 62 | // 仅default驱动可以多次注册,实际调用最后一次注册的default驱动 63 | // 其他驱动名称仅允许注册一次,不允许重复注册相同名称的驱动 64 | Cache::instance()->addDriver($fileDriver,'default'); 65 | 66 | // 从缓存管理器单例中获取任意名字的驱动,不指定名字为获取default驱动 67 | $cache = Cache::instance()->getDriver('default'); 68 | 69 | ``` 70 | 71 | ### Redis驱动 72 | 73 | 该驱动使用Swoole内置的Redis协程客户端,内部已实现自动连接池管理,可以在协程模式下安全的使用 74 | 75 | > 注意: 当一次请求存在多个协程时(比如说手动create了协程),则会为每一个协程都分配一个链接,Memcache驱动也一样,实际上不会影响使用,因为并没有用到事务相关特性:),但需要注意避免创建大量嵌套协程导致瞬间取空连接池 76 | 77 | ```php 78 | 79 | // 请注意先Use要使用的驱动类和配置类 80 | use EasySwoole\Cache\Config\RedisConfig; 81 | use EasySwoole\Cache\Drivers\Redis as RedisDriver; 82 | 83 | // 需要协程环境(在EasySwoole框架内无需手动创建协程) 84 | Coroutine::create(function () { 85 | 86 | // Redis的Config可以同时配置链接池相关的设置项 87 | $redisDriver = new RedisDriver((new RedisConfig([ 88 | 89 | // 链接配置项 90 | 'db' => 0, // 有多个DB时可以选择使用的DB 默认选择0号DB 91 | 'host' => '127.0.0.1', // 默认是连接本地Redis 92 | 'port' => 6379, // 默认的端口 93 | 'auth' => null, // 默认没有密码 94 | 'connectTimeout' => 1, // 连接到服务器的超时时间 95 | 'execTimeout' => 1, // 执行操作的超时时间 96 | 'reconnect' => 3, // 如果连接断开自动尝试x次重连 97 | 98 | // 链接池配置项 99 | 'intervalCheckTime' => 30 * 1000, // 池对象回收检测周期 100 | 'maxIdleTime' => 15, // 连接最大空闲时间(超时释放) 101 | 'maxObjectNum' => 20, // 池最大连接象数量 102 | 'minObjectNum' => 5, // 保持的最小连接数量 103 | 'getObjectTimeout' => 3.0 // 池为空时获取连接最大等待时间 104 | 105 | ]))); 106 | 107 | Cache::instance()->addDriver($redisDriver, 'redis'); 108 | $cache = Cache::instance()->getDriver('redis'); 109 | }); 110 | 111 | ``` 112 | 113 | ### Memcache驱动 114 | 115 | 以Swoole的协程Client实现了Memcache的TCP二进制驱动,不依赖PHP本身的Memcached驱动和libmemcache,同样需要协程环境,二进制协议仅支持Memcached(即Server)v1.3版本以上 116 | 117 | ```php 118 | 119 | // 请注意先Use要使用的驱动类和配置类 120 | use EasySwoole\Cache\Config\MemcacheConfig; 121 | use EasySwoole\Cache\Drivers\Memcache as MemcacheDriver; 122 | 123 | // 需要协程环境(在EasySwoole框架内无需手动创建协程) 124 | Coroutine::create(function () { 125 | 126 | // Memcache的Config可以同时配置链接池相关的设置项 127 | $memcacheDriver = new MemcacheDriver((new MemcacheConfig([ 128 | 129 | // 链接配置项 130 | 'host' => '127.0.0.1', // 默认是连接本地Memcache 131 | 'port' => 11211, // 默认的端口 132 | 133 | // 链接池配置项 134 | 'intervalCheckTime' => 30 * 1000, // 池对象回收检测周期 135 | 'maxIdleTime' => 15, // 连接最大空闲时间(超时释放) 136 | 'maxObjectNum' => 20, // 池最大连接象数量 137 | 'minObjectNum' => 5, // 保持的最小连接数量 138 | 'getObjectTimeout' => 3.0 // 池为空时获取连接最大等待时间 139 | 140 | ]))); 141 | 142 | Cache::instance()->addDriver($memcacheDriver, 'memcache'); 143 | $cache = Cache::instance()->getDriver('memcache'); 144 | }); 145 | 146 | ``` 147 | 148 | ### SwooleTable 149 | 150 | 基于SwooleTable内存表实现的快速内存缓存,注意该缓存暂不支持数据落地,服务停止后缓存数据会立即丢失,适用于做一些计数器类或能容忍缓存重建而不雪崩的一些场景(如储存公众号Token等),由于Table创建时需要立即申请内存,请确保足够的内存,否则会因Table创建失败导致不可用 151 | 152 | > 注意: 由于Swoole进程隔离特性,当使用SwooleTable作为驱动时,需要在Sw的全局期进行驱动的初始化,否则缓存数据会被隔离在各个独立的Worker进程中,另外各配置项受到SwooleTable本身的限制,不能超过本身的限制最大值 153 | 154 | ```php 155 | 156 | // 请注意先Use要使用的驱动类和配置类 157 | use EasySwoole\Cache\Config\SwooleTableConfig; 158 | use EasySwoole\Cache\Drivers\SwooleTable as SwooleTableDriver; 159 | 160 | // 需要协程环境(在EasySwoole框架内无需手动创建协程) 161 | Coroutine::create(function () { 162 | 163 | // 可以配置Table相关的一些配置项 164 | $swooleTableDriver = new SwooleTableDriver((new SwooleTableConfig([ 165 | 166 | 'tableSize' => 4096, // 能容纳的总Key数量(由于哈希冲突,实际储存量会比该值小一点) 167 | 'maxKeySize' => 512, // Key支持的最大长度(字节) 168 | 'maxValueSize' => 4096, // Value支持的最大长度(字节) 169 | 'recycleInterval' => 1000, // 超时Key回收周期(ms) 170 | 'conflictProportion' => 0.2, // 允许哈希冲突的最大比例 171 | 172 | ]))); 173 | 174 | Cache::instance()->addDriver($swooleTableDriver, 'swTable'); 175 | $cache = Cache::instance()->getDriver('swTable'); 176 | }); 177 | 178 | ``` 179 | 180 | ### 关于配置项 181 | 182 | 配置项均由EasySwoole/Spl/SplBean实现,因此可以链式设置和获取 183 | 184 | ```php 185 | 186 | use EasySwoole\Cache\Config\SwooleTableConfig; 187 | 188 | $tableConfig = new SwooleTableConfig; 189 | 190 | $tableConfig 191 | ->setTableSize(4096) 192 | ->setMaxKeySize(512) 193 | ->setMaxValueSize(512); 194 | 195 | ``` 196 | 197 | ### 单元测试 198 | 199 | 尚未支持单元测试,欢迎提交Pull Request! 200 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "easyswoole/cache", 3 | "description": "易用的缓存工具类(FileSystem/Redis/Memcahced/SwooleTable)支持协程特性", 4 | "type": "library", 5 | "license": "Apache-2.0", 6 | "authors": [ 7 | { 8 | "name": "evalor", 9 | "email": "mipone@foxmail.com" 10 | }, 11 | { 12 | "name": "lw", 13 | "email": "491284539@qq.com" 14 | } 15 | ], 16 | "require": { 17 | "ext-swoole": "^4.4.0", 18 | "psr/simple-cache": "^1.0", 19 | "easyswoole/component": "^2.0", 20 | "opis/closure": "^3.4", 21 | "easyswoole/redis-pool": "^2.2" 22 | }, 23 | "autoload": { 24 | "psr-4": { 25 | "EasySwoole\\Cache\\": "src/", 26 | "EasySwoole\\Cache\\Test\\": "tests/" 27 | } 28 | }, 29 | "require-dev": { 30 | "easyswoole/swoole-ide-helper": "^1.3", 31 | "easyswoole/phpunit": "^1.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Cache.php: -------------------------------------------------------------------------------- 1 | drivers)) { 70 | throw new CacheException("Driver name {$driverName} has been used"); 71 | } 72 | 73 | // 注册到当前缓存容器中 74 | if ($driver instanceof AbstractDriver) { 75 | $this->drivers[$driverName] = $driver; 76 | 77 | return true; 78 | } 79 | 80 | throw new CacheException("Driver name {$driverName} must be instance of AbstractDriver"); 81 | } 82 | 83 | /** 84 | * 获取一个驱动类. 85 | * @param string $driverName 86 | * @return AbstractDriver 87 | * @throws CacheException 88 | */ 89 | public function getDriver($driverName = 'default') 90 | { 91 | // 如果要获取的驱动是默认驱动 且默认驱动尚未注册 则自动注册默认驱动 92 | if (!array_key_exists($driverName, $this->drivers)) { 93 | if ($driverName === 'default') { 94 | $this->drivers['default'] = new FileDriver(); 95 | 96 | return $this->drivers['default']; 97 | } 98 | 99 | throw new CacheException("Driver name {$driverName} does not exist"); 100 | } 101 | 102 | return $this->drivers[$driverName]; 103 | } 104 | 105 | /** 106 | * 静态化调用. 107 | * @param $name 108 | * @param $arguments 109 | * @return mixed 110 | * @throws CacheException 111 | */ 112 | public static function __callStatic($name, $arguments) 113 | { 114 | return self::instance()->getDriver('default')->$name(...$arguments); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/Config/FileConfig.php: -------------------------------------------------------------------------------- 1 | initDefaultConfig(); 30 | parent::__construct($data, $autoCreateProperty); 31 | } 32 | 33 | /** 34 | * 设置默认的配置值 35 | * @return void 36 | */ 37 | private function initDefaultConfig() 38 | { 39 | $this->cachePath = sys_get_temp_dir().'/SwkCache'; 40 | $this->cachePrefix = null; 41 | $this->defaultExpire = 0; 42 | } 43 | 44 | /** 45 | * 获取缓存目录. 46 | * @return mixed 47 | */ 48 | public function getCachePath() 49 | { 50 | return $this->cachePath; 51 | } 52 | 53 | /** 54 | * 设置缓存目录. 55 | * @param string $cachePath 56 | */ 57 | public function setCachePath(string $cachePath): void 58 | { 59 | $this->cachePath = $cachePath; 60 | } 61 | 62 | /** 63 | * 获取缓存前缀 64 | * @return mixed 65 | */ 66 | public function getCachePrefix() 67 | { 68 | return $this->cachePrefix; 69 | } 70 | 71 | /** 72 | * 设置缓存前缀 73 | * @param string $cachePrefix 74 | */ 75 | public function setCachePrefix(string $cachePrefix): void 76 | { 77 | $this->cachePrefix = $cachePrefix; 78 | } 79 | 80 | /** 81 | * 获取缓存超时. 82 | * @return mixed 83 | */ 84 | public function getDefaultExpire() 85 | { 86 | return $this->defaultExpire; 87 | } 88 | 89 | /** 90 | * 设置缓存超时. 91 | * @param int $defaultExpire 92 | */ 93 | public function setDefaultExpire(int $defaultExpire): void 94 | { 95 | $this->defaultExpire = $defaultExpire; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Config/SwooleTableConfig.php: -------------------------------------------------------------------------------- 1 | tableSize; 35 | } 36 | 37 | /** 38 | * TableSize Setter. 39 | * @param int $tableSize 40 | * @return SwooleTableConfig 41 | */ 42 | public function setTableSize(int $tableSize): SwooleTableConfig 43 | { 44 | $this->tableSize = $tableSize; 45 | 46 | return $this; 47 | } 48 | 49 | /** 50 | * MaxKeySize Getter. 51 | * @return int 52 | */ 53 | public function getMaxKeySize(): int 54 | { 55 | return $this->maxKeySize; 56 | } 57 | 58 | /** 59 | * MaxKeySize Setter. 60 | * @param int $maxKeySize 61 | * @return SwooleTableConfig 62 | */ 63 | public function setMaxKeySize(int $maxKeySize): SwooleTableConfig 64 | { 65 | $this->maxKeySize = $maxKeySize; 66 | 67 | return $this; 68 | } 69 | 70 | /** 71 | * MaxValueSize Getter. 72 | * @return int 73 | */ 74 | public function getMaxValueSize(): int 75 | { 76 | return $this->maxValueSize; 77 | } 78 | 79 | /** 80 | * MaxValueSize Setter. 81 | * @param int $maxValueSize 82 | * @return SwooleTableConfig 83 | */ 84 | public function setMaxValueSize(int $maxValueSize): SwooleTableConfig 85 | { 86 | $this->maxValueSize = $maxValueSize; 87 | 88 | return $this; 89 | } 90 | 91 | /** 92 | * RecycleInterval Getter. 93 | * @return int 94 | */ 95 | public function getRecycleInterval(): int 96 | { 97 | return $this->recycleInterval; 98 | } 99 | 100 | /** 101 | * RecycleInterval Setter. 102 | * @param int $recycleInterval 103 | * @return SwooleTableConfig 104 | */ 105 | public function setRecycleInterval(int $recycleInterval): SwooleTableConfig 106 | { 107 | $this->recycleInterval = $recycleInterval; 108 | 109 | return $this; 110 | } 111 | 112 | /** 113 | * ConflictProportion Getter. 114 | * @return float 115 | */ 116 | public function getConflictProportion(): float 117 | { 118 | return $this->conflictProportion; 119 | } 120 | 121 | /** 122 | * ConflictProportion Setter. 123 | * @param float $conflictProportion 124 | * @return SwooleTableConfig 125 | */ 126 | public function setConflictProportion(float $conflictProportion): SwooleTableConfig 127 | { 128 | $this->conflictProportion = $conflictProportion; 129 | 130 | return $this; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/Drivers/AbstractDriver.php: -------------------------------------------------------------------------------- 1 | get($key, $default); 74 | } 75 | 76 | return $result; 77 | } 78 | 79 | /** 80 | * 批量设置缓存. 81 | * @param iterable $values 82 | * @param null $ttl 83 | * @return bool 84 | */ 85 | public function setMultiple($values, $ttl = null) 86 | { 87 | foreach ($values as $key => $val) { 88 | $result = $this->set($key, $val, $ttl); 89 | if (false === $result) { 90 | return false; 91 | } 92 | } 93 | 94 | return true; 95 | } 96 | 97 | /** 98 | * 批量删除缓存. 99 | * @param iterable $keys 100 | * @return bool 101 | */ 102 | public function deleteMultiple($keys) 103 | { 104 | foreach ($keys as $key) { 105 | $result = $this->delete($key); 106 | if (false === $result) { 107 | return false; 108 | } 109 | } 110 | 111 | return true; 112 | } 113 | 114 | /** 115 | * 序列化数据. 116 | * @param $data 117 | * @return string 118 | */ 119 | protected function serialize($data): string 120 | { 121 | SerializableClosure::enterContext(); 122 | SerializableClosure::wrapClosures($data); 123 | $data = serialize($data); 124 | SerializableClosure::exitContext(); 125 | 126 | return $data; 127 | } 128 | 129 | /** 130 | * 反序列化数据. 131 | * @param string $data 132 | * @return mixed 133 | */ 134 | protected function unserialize(string $data) 135 | { 136 | SerializableClosure::enterContext(); 137 | $data = unserialize($data); 138 | SerializableClosure::unwrapClosures($data); 139 | SerializableClosure::exitContext(); 140 | 141 | return $data; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/Drivers/File.php: -------------------------------------------------------------------------------- 1 | cachePath = $cacheConfig->getCachePath(); 42 | $this->cachePrefix = $cacheConfig->getCachePrefix(); 43 | $this->defaultExpire = $cacheConfig->getDefaultExpire(); 44 | 45 | clearstatcache(true); 46 | if (substr($this->cachePath, -1) != DIRECTORY_SEPARATOR) { 47 | $this->cachePath .= DIRECTORY_SEPARATOR; 48 | } 49 | 50 | if (!file_exists($this->cachePath)) { 51 | if (!\EasySwoole\Utility\File::createDirectory($this->cachePath)) { 52 | throw new Exception('File Cache Driver: directory create failed!'); 53 | } 54 | } 55 | } 56 | 57 | /** 58 | * 获取存储文件名. 59 | * @param $name 60 | * @param bool $auto 61 | * @return string 62 | */ 63 | protected function getCacheKey($name, $auto = false) 64 | { 65 | $name = md5($name); 66 | if ($this->cachePrefix) { 67 | $name = $this->cachePrefix.DIRECTORY_SEPARATOR.$name; 68 | } 69 | $filename = $this->cachePath.$name.'.php'; 70 | $dir = dirname($filename); 71 | if ($auto && !is_dir($dir)) { 72 | \EasySwoole\Utility\File::createDirectory($dir); 73 | } 74 | 75 | return $filename; 76 | } 77 | 78 | /** 79 | * 写入缓存. 80 | * @param string $key 81 | * @param mixed $value 82 | * @param null $expire 83 | * @return bool 84 | */ 85 | public function set($key, $value, $expire = null) 86 | { 87 | if (is_null($expire)) { 88 | $expire = $this->defaultExpire; 89 | } 90 | $filename = $this->getCacheKey($key, true); 91 | $data = $this->serialize($value); 92 | $data = "\n".$data; 93 | $result = file_put_contents($filename, $data, LOCK_EX); 94 | if ($result) { 95 | clearstatcache(); 96 | 97 | return true; 98 | } else { 99 | return false; 100 | } 101 | } 102 | 103 | /** 104 | * 读取缓存. 105 | * @param string $key 106 | * @param null $default 107 | * @return bool|mixed|string 108 | */ 109 | public function get($key, $default = null) 110 | { 111 | $filename = $this->getCacheKey($key); 112 | if (!is_file($filename)) { 113 | return $default; 114 | } 115 | $content = file_get_contents($filename); 116 | $this->expire = null; 117 | if (false !== $content) { 118 | $expire = (int) substr($content, 8, 12); 119 | if (0 != $expire && time() > filemtime($filename) + $expire) { 120 | $this->unlink($filename); 121 | 122 | return $default; 123 | } 124 | $this->expire = $expire; 125 | $content = substr($content, 32); 126 | $content = $this->unserialize($content); 127 | 128 | return $content; 129 | } else { 130 | return $default; 131 | } 132 | } 133 | 134 | /** 135 | * 自增缓存(针对数值缓存). 136 | * @param $key 137 | * @param int $step 138 | * @return bool|int|mixed|string 139 | */ 140 | public function inc($key, $step = 1) 141 | { 142 | if ($this->has($key)) { 143 | $value = $this->get($key) + $step; 144 | $expire = $this->expire; 145 | } else { 146 | $value = $step; 147 | $expire = 0; 148 | } 149 | 150 | return $this->set($key, $value, $expire) ? $value : false; 151 | } 152 | 153 | /** 154 | * 自减缓存(针对数值缓存). 155 | * @param $key 156 | * @param int $step 157 | * @return bool|int|mixed|string 158 | */ 159 | public function dec($key, $step = 1) 160 | { 161 | if ($this->has($key)) { 162 | $value = $this->get($key) - $step; 163 | $expire = $this->expire; 164 | } else { 165 | $value = -$step; 166 | $expire = 0; 167 | } 168 | 169 | return $this->set($key, $value, $expire) ? $value : false; 170 | } 171 | 172 | /** 173 | * 判断缓存是否存在. 174 | * @param string $key 175 | * @return bool 176 | */ 177 | public function has($key) 178 | { 179 | return $this->get($key) ? true : false; 180 | } 181 | 182 | /** 183 | * 删除缓存. 184 | * @param string $key 185 | * @return bool 186 | */ 187 | public function delete($key) 188 | { 189 | $filename = $this->getCacheKey($key); 190 | 191 | return $this->unlink($filename); 192 | } 193 | 194 | /** 195 | * 清除缓存. 196 | * @return bool 197 | */ 198 | public function clear() 199 | { 200 | $files = (array) glob($this->cachePath.($this->cachePrefix ? $this->cachePrefix.DIRECTORY_SEPARATOR : '').'*'); 201 | foreach ($files as $path) { 202 | if (is_dir($path)) { 203 | $matches = glob($path.'/*.php'); 204 | if (is_array($matches)) { 205 | array_map('unlink', $matches); 206 | } 207 | } else { 208 | unlink($path); 209 | } 210 | } 211 | 212 | return true; 213 | } 214 | 215 | /** 216 | * 判断文件是否存在后,删除. 217 | * @param $path 218 | * @return bool 219 | */ 220 | private function unlink($path) 221 | { 222 | return is_file($path) && unlink($path); 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/Drivers/Memcache.php: -------------------------------------------------------------------------------- 1 | pool = $pool; 40 | } 41 | 42 | 43 | /** 44 | * @param string $key 45 | * @param null $default 46 | * @return false|mixed 47 | * @throws PoolEmpty 48 | * @throws \Throwable 49 | */ 50 | public function get($key, $default = null) 51 | { 52 | return $this->pool->invoke(function (\EasySwoole\Memcache\Memcache $memcache) use ($key, $default) { 53 | return $memcache->get($key) ?? $default; 54 | }); 55 | } 56 | 57 | /** 58 | * @param string $key 59 | * @param mixed $value 60 | * @param null $ttl 61 | * @return bool|mixed 62 | * @throws PoolEmpty 63 | * @throws \Throwable 64 | */ 65 | public function set($key, $value, $ttl = null) 66 | { 67 | return $this->pool->invoke(function (\EasySwoole\Memcache\Memcache $memcache) use ($key, $value, $ttl) { 68 | return $memcache->set($key, $value, $ttl); 69 | }); 70 | } 71 | 72 | /** 73 | * @param string $key 74 | * @return bool|mixed 75 | * @throws PoolEmpty 76 | * @throws \Throwable 77 | */ 78 | public function delete($key) 79 | { 80 | return $this->pool->invoke(function (\EasySwoole\Memcache\Memcache $memcache) use ($key) { 81 | return $memcache->delete($key); 82 | }); 83 | } 84 | 85 | /** 86 | * @return bool|mixed 87 | * @throws PoolEmpty 88 | * @throws \Throwable 89 | */ 90 | public function clear() 91 | { 92 | return $this->pool->invoke(function (\EasySwoole\Memcache\Memcache $memcache) { 93 | return $memcache->flush(); 94 | }); 95 | } 96 | 97 | /** 98 | * @param string $key 99 | * @return bool|mixed 100 | * @throws PoolEmpty 101 | * @throws \Throwable 102 | */ 103 | public function has($key) 104 | { 105 | return $this->pool->invoke(function (\EasySwoole\Memcache\Memcache $memcache) use ($key) { 106 | $reqPack = new Package(['opcode' => Opcode::OP_GET, 'key' => $key]); 107 | $resPack = $memcache->sendCommand($reqPack); 108 | 109 | if ($resPack->getStatus() === Status::STAT_KEY_NOTFOUND) { 110 | return false; 111 | } 112 | 113 | return true; 114 | }); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/Drivers/Redis.php: -------------------------------------------------------------------------------- 1 | pool = $pool; 33 | } 34 | 35 | /** 36 | * @param string $key 37 | * @param mixed $value 38 | * @param null $expire 39 | * @return bool|mixed 40 | * @throws Throwable 41 | * @throws PoolEmpty 42 | */ 43 | public function set($key, $value, $expire = null) 44 | { 45 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $value, $expire) { 46 | if ($expire) { 47 | return $redis->setEx($key, intval($expire), $value); 48 | } else { 49 | return $redis->set($key, $value); 50 | } 51 | }); 52 | 53 | } 54 | 55 | /** 56 | * @param string $key 57 | * @param null $default 58 | * @return mixed|null 59 | * @throws Throwable 60 | * @throws PoolEmpty 61 | */ 62 | public function get($key, $default = null) 63 | { 64 | $value = $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key) { 65 | return $redis->get($key); 66 | }); 67 | 68 | return $value === false ? $default : $value; 69 | } 70 | 71 | /** 72 | * @param $key 73 | * @param int $step 74 | * @return false|mixed 75 | * @throws PoolEmpty 76 | * @throws Throwable 77 | */ 78 | public function inc($key, $step = 1) 79 | { 80 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $step) { 81 | return $redis->incrBy($key, $step); 82 | }); 83 | } 84 | 85 | /** 86 | * @param $key 87 | * @param int $step 88 | * @return false|mixed 89 | * @throws PoolEmpty 90 | * @throws Throwable 91 | */ 92 | public function dec($key, $step = 1) 93 | { 94 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $step) { 95 | return $redis->decrBy($key, $step); 96 | }); 97 | } 98 | 99 | /** 100 | * @param string $key 101 | * @return bool|mixed 102 | * @throws PoolEmpty 103 | * @throws Throwable 104 | */ 105 | public function has($key) 106 | { 107 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key) { 108 | return $redis->exists($key); 109 | }); 110 | } 111 | 112 | /** 113 | * @param string $key 114 | * @return bool|mixed 115 | * @throws PoolEmpty 116 | * @throws Throwable 117 | */ 118 | public function delete($key) 119 | { 120 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) use ($key) { 121 | return $redis->del($key); 122 | }); 123 | } 124 | 125 | /** 126 | * @return bool|mixed 127 | * @throws PoolEmpty 128 | * @throws Throwable 129 | */ 130 | public function clear() 131 | { 132 | return $this->pool->invoke(function (\EasySwoole\Redis\Redis $redis) { 133 | return $redis->flushDb(); 134 | }); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/Drivers/SwooleTable.php: -------------------------------------------------------------------------------- 1 | tableName = Random::character(32); 41 | if (!($swooleConfig instanceof SwooleTableConfig)) { 42 | $swooleConfig = new SwooleTableConfig(); 43 | } 44 | 45 | $this->swooleConfig = $swooleConfig; 46 | 47 | // 定义储存表的结构 48 | $this->tableStructure = [ 49 | 'key' => ['type' => Table::TYPE_STRING, 'size' => $swooleConfig->getMaxKeySize()], 50 | 'value' => ['type' => Table::TYPE_STRING, 'size' => $swooleConfig->getMaxValueSize()], 51 | 'expire' => ['type' => Table::TYPE_INT, 'size' => 4], 52 | 'serialize' => ['type' => Table::TYPE_INT, 'size' => 1], 53 | ]; 54 | 55 | // 创建数据存储表 56 | $this->initSwooleTable(); 57 | $this->initRecycleTimer($swooleConfig->getRecycleInterval()); 58 | } 59 | 60 | /** 61 | * 初始化数据表. 62 | * @return mixed 63 | */ 64 | private function initSwooleTable() 65 | { 66 | // 如果表已存在直接释放表 67 | if ($this->table instanceof Table) { 68 | $this->table->destroy(); 69 | unset($this->table); 70 | } 71 | 72 | // 创建一个新实例并进行初始化 73 | $this->table = new Table($this->swooleConfig->getTableSize(), $this->swooleConfig->getConflictProportion()); 74 | foreach ($this->tableStructure as $columnName => $columnStruct) { 75 | $this->table->column($columnName, $columnStruct['type'], $columnStruct['size']); 76 | } 77 | 78 | return $this->table->create(); 79 | } 80 | 81 | /** 82 | * 周期性回收. 83 | * @param int $interval 84 | */ 85 | private function initRecycleTimer($interval = 1000) 86 | { 87 | $this->timer = Timer::getInstance()->loop($interval, function () { 88 | $currentTime = time(); 89 | foreach ($this->table as $cacheItem) { 90 | if ($cacheItem['expire'] !== 0 && $cacheItem['expire'] < $currentTime) { 91 | $this->table->del($cacheItem['key']); 92 | } 93 | } 94 | }); 95 | } 96 | 97 | /** 98 | * 获取一个值 99 | * @param string $key 100 | * @param null $default 101 | * @return mixed 102 | */ 103 | public function get($key, $default = null) 104 | { 105 | $value = $this->table->get($key); 106 | if ($value !== false) { 107 | return $value['serialize'] === 1 ? $this->unserialize($value['value']) : $value; 108 | } 109 | 110 | return $default; 111 | } 112 | 113 | /** 114 | * 设置一个值 115 | * @param string $key 116 | * @param mixed $value 117 | * @param null $ttl 118 | * @return bool|mixed 119 | */ 120 | public function set($key, $value, $ttl = null) 121 | { 122 | list($isSerialize, $setValue) = $this->processValue($value); 123 | 124 | return $this->table->set($key, [ 125 | 'key' => $key, 126 | 'value' => $setValue, 127 | 'expire' => is_null($ttl) ? 0 : intval($ttl) + time(), 128 | 'serialize' => $isSerialize, 129 | ]); 130 | } 131 | 132 | /** 133 | * 删除一个值 134 | * @param string $key 135 | * @return bool|mixed 136 | */ 137 | public function delete($key) 138 | { 139 | return $this->table->del($key); 140 | } 141 | 142 | /** 143 | * 清空并重建表. 144 | * @return bool|mixed 145 | */ 146 | public function clear() 147 | { 148 | return $this->initSwooleTable(); 149 | } 150 | 151 | /** 152 | * 值是否存在. 153 | * @param string $key 154 | * @return bool|mixed 155 | */ 156 | public function has($key) 157 | { 158 | return $this->table->exist($key); 159 | } 160 | 161 | /** 162 | * 缓存值序列化. 163 | * @param mixed $value 164 | * @return array 165 | */ 166 | private function processValue($value) 167 | { 168 | if (is_array($value) || is_object($value)) { 169 | return [1, $this->serialize($value)]; 170 | } 171 | 172 | return [0, $value]; 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/Exception/CacheException.php: -------------------------------------------------------------------------------- 1 | sys_get_temp_dir(), // 缓存目录(默认为PHP系统缓存) 35 | 'cachePrefix' => null, // 默认的缓存前缀 不同前缀分目录存放 36 | 'defaultExpire' => 0, // 默认过期时间 设置为0永不过期 37 | ])); 38 | // 注册驱动时不指定驱动名称,则为注册default驱动 39 | // 仅default驱动可以多次注册,实际调用最后一次注册的default驱动 40 | // 其他驱动名称仅允许注册一次,不允许重复注册相同名称的驱动 41 | Cache::instance()->addDriver($fileDriver, 'default'); 42 | 43 | // 从缓存管理器单例中获取任意名字的驱动,不指定名字为获取default驱动 44 | Cache::instance()->getDriver('default'); 45 | } 46 | 47 | public function testSet() 48 | { 49 | Cache::set('key', 1); 50 | $this->assertEquals(1, Cache::get('key')); 51 | } 52 | 53 | public function testGetWithTTL() 54 | { 55 | Cache::set('keyGetWithTTL', 2, 1); 56 | $this->assertEquals(2, Cache::get('keyGetWithTTL')); 57 | sleep(2); 58 | $this->assertEquals('', Cache::get('keyGetWithTTL')); 59 | } 60 | 61 | public function testInc() 62 | { 63 | Cache::set('inc', 1); 64 | Cache::inc('inc'); 65 | $this->assertEquals(2, Cache::get('inc')); 66 | } 67 | 68 | public function testDec() 69 | { 70 | Cache::set('dec', 2); 71 | Cache::dec('dec'); 72 | $this->assertEquals(1, Cache::get('dec')); 73 | } 74 | 75 | public function testHas() 76 | { 77 | Cache::set('has', 3); 78 | $this->assertEquals(true, Cache::has('has')); 79 | } 80 | 81 | public function testDelete() 82 | { 83 | Cache::set('delete', 4); 84 | $this->assertEquals(4, Cache::get('delete')); 85 | Cache::delete('delete'); 86 | $this->assertEquals(false, Cache::has('delete')); 87 | } 88 | 89 | public function testSetMultiple() 90 | { 91 | Cache::setMultiple([ 92 | 'set1' => 1, 93 | 'set2' => 2, 94 | ], 10); 95 | $this->assertEquals(['set1' => 1], Cache::getMultiple(['set1'], 0)); 96 | $this->assertEquals(['set1' => 1, 'set2' => 2], Cache::getMultiple(['set1', 'set2'], 0)); 97 | $this->assertEquals(['set3' => 0], Cache::getMultiple(['set3'], 0)); 98 | } 99 | 100 | public function testDeleteMultiple() 101 | { 102 | Cache::setMultiple([ 103 | 'set4' => 4, 104 | 'set5' => 5, 105 | ]); 106 | $this->assertEquals(['set4' => 4, 'set5' => 5], Cache::getMultiple(['set4', 'set5'], 0)); 107 | Cache::deleteMultiple(['set4', 'set5']); 108 | $this->assertEquals(['set4' => 0, 'ser5' => 0], Cache::getMultiple(['set4', 'ser5'])); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /tests/MemcachedDriverTest.php: -------------------------------------------------------------------------------- 1 | '127.0.0.1' 29 | ]))); 30 | $driver = new Memcache($pool); 31 | Cache::instance()->addDriver($driver, 'memcache'); 32 | self::$cache = Cache::instance()->getDriver('memcache'); 33 | } 34 | 35 | public function testGet() 36 | { 37 | $this->assertEquals('no', self::$cache->get('key1', 'no')); 38 | } 39 | 40 | public function testSet() 41 | { 42 | self::$cache->set('key', 1); 43 | $this->assertEquals(1, self::$cache->get('key')); 44 | } 45 | 46 | public function testHas() 47 | { 48 | Cache::set('has', 3); 49 | $this->assertEquals(true, Cache::has('has')); 50 | $this->assertEquals(false, Cache::has('has1')); 51 | } 52 | 53 | public function testDelete() 54 | { 55 | Cache::set('delete', 4); 56 | $this->assertEquals(4, Cache::get('delete')); 57 | Cache::delete('delete'); 58 | $this->assertEquals(false, Cache::has('delete')); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /tests/RedisDriverTest.php: -------------------------------------------------------------------------------- 1 | '127.0.0.1', 28 | 'port' => 6379 29 | ])); 30 | $redisDriver = new Redis($pool); 31 | Cache::instance()->addDriver($redisDriver, 'redis'); 32 | self::$cache = Cache::instance()->getDriver('redis'); 33 | } 34 | 35 | 36 | public function testSet() 37 | { 38 | self::$cache->set('key', 1); 39 | $this->assertEquals(1, self::$cache->get('key')); 40 | } 41 | 42 | public function testGetWithTTL() 43 | { 44 | self::$cache->set('keyGetWithTTL', 2, 1); 45 | $this->assertEquals(2, self::$cache->get('keyGetWithTTL')); 46 | sleep(2); 47 | $this->assertEquals('', self::$cache->get('keyGetWithTTL')); 48 | } 49 | 50 | public function testInc() 51 | { 52 | Cache::set('inc', 1); 53 | Cache::inc('inc'); 54 | $this->assertEquals(2, Cache::get('inc')); 55 | } 56 | 57 | public function testDec() 58 | { 59 | Cache::set('dec', 2); 60 | Cache::dec('dec'); 61 | $this->assertEquals(1, Cache::get('dec')); 62 | } 63 | 64 | public function testHas() 65 | { 66 | Cache::set('has', 3); 67 | $this->assertEquals(true, Cache::has('has')); 68 | } 69 | 70 | public function testDelete() 71 | { 72 | Cache::set('delete', 4); 73 | $this->assertEquals(4, Cache::get('delete')); 74 | Cache::delete('delete'); 75 | $this->assertEquals(false, Cache::has('delete')); 76 | } 77 | 78 | public function testSetMultiple() 79 | { 80 | Cache::setMultiple([ 81 | 'set1' => 1, 82 | 'set2' => 2, 83 | ], 10); 84 | $this->assertEquals(['set1' => 1], Cache::getMultiple(['set1'], 0)); 85 | $this->assertEquals(['set1' => 1, 'set2' => 2], Cache::getMultiple(['set1', 'set2'], 0)); 86 | $this->assertEquals(['set3' => 0], Cache::getMultiple(['set3'], 0)); 87 | } 88 | 89 | public function testDeleteMultiple() 90 | { 91 | Cache::setMultiple([ 92 | 'set4' => 4, 93 | 'set5' => 5, 94 | ]); 95 | $this->assertEquals(['set4' => 4, 'set5' => 5], Cache::getMultiple(['set4', 'set5'], 0)); 96 | Cache::deleteMultiple(['set4', 'set5']); 97 | $this->assertEquals(['set4' => 0, 'ser5' => 0], Cache::getMultiple(['set4', 'ser5'])); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /tests/SwooleTableDriverTest.php: -------------------------------------------------------------------------------- 1 | 4096, // 能容纳的总Key数量(由于哈希冲突,实际储存量会比该值小一点) 38 | 'maxKeySize' => 512, // Key支持的最大长度(字节) 39 | 'maxValueSize' => 4096, // Value支持的最大长度(字节) 40 | 'recycleInterval' => 1000, // 超时Key回收周期(ms) 41 | 'conflictProportion' => 0.2, // 允许哈希冲突的最大比例 42 | 43 | ]))); 44 | 45 | Cache::instance()->addDriver($swooleTableDriver, 'swTable'); 46 | $this->cache = Cache::instance()->getDriver('swTable'); 47 | } 48 | 49 | public function testSet() 50 | { 51 | $this->cache->set('key', 1); 52 | $this->assertEquals([ 53 | 'key' => 'key', 54 | 'value' => 1, 55 | 'expire' => 0, 56 | 'serialize' => 0, 57 | ], $this->cache->get('key')); 58 | } 59 | 60 | public function testHas() 61 | { 62 | Cache::set('has', 3); 63 | $this->assertEquals(true, Cache::has('has')); 64 | } 65 | 66 | public function testDelete() 67 | { 68 | Cache::set('delete', 4); 69 | $this->assertEquals(4, Cache::get('delete')); 70 | Cache::delete('delete'); 71 | $this->assertEquals(false, Cache::has('delete')); 72 | } 73 | } 74 | --------------------------------------------------------------------------------