laravel自定义缓存memcache(自带memcached,windows不支持)
Posted winstonsias
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel自定义缓存memcache(自带memcached,windows不支持)相关的知识,希望对你有一定的参考价值。
1、首先弄清楚memcache和memcached的区别(自行搜索)
2、安装memcache服务端(参照https://www.cnblogs.com/winstonsias/p/10190745.html)及php扩展(参照https://www.cnblogs.com/winstonsias/p/10193781.html)
3、添加服务提供类 MemcacheServiceProvider ,记得在app.php配置文件添加提供者注册
1 namespace App\\Providers; 2 3 use Cache; 4 use App\\Extensions\\MemcacheStore; 5 use Illuminate\\Support\\ServiceProvider; 6 7 class MemcacheServiceProvider extends ServiceProvider 8 { 9 public function boot() 10 { 11 Cache::extend(\'memcache\', function ($app) { 12 return Cache::repository(new MemcacheStore($app[\'memcache.connector\'])); 13 }); 14 } 15 16 public function register() 17 { 18 //注册memcache连接的单例 19 $this->app->singleton(\'memcache.connector\', function ($app) { 20 $config = $app[\'config\']["cache.stores.memcache"]; 21 $servers = $config[\'servers\'][0]; 22 return memcache_connect($servers[\'host\'], $servers[\'port\']); 23 }); 24 } 25 26 27 }
4、完善存储类MemcacheStore(可在app添加Extensions文件夹存放)
1 namespace App\\Extensions; 2 class MemcacheStore implements \\Illuminate\\Contracts\\Cache\\Store 3 { 4 //memcache资源 5 protected $memcache_conn; 6 public function __construct($conn) 7 { 8 $this->memcache_conn=$conn; 9 } 10 11 public function __destruct() 12 { 13 // TODO: Implement __destruct() method. 14 $this->memcache_conn=null;//释放资源 15 } 16 17 public function get($key) 18 { 19 return $this->memcache_conn->get($key); 20 } 21 22 public function put($key, $value, $minutes) 23 { 24 } 25 26 public function increment($key, $value = 1) 27 { 28 } 29 30 public function decrement($key, $value = 1) 31 { 32 } 33 34 public function forever($key, $value) 35 { 36 } 37 38 public function forget($key) 39 { 40 } 41 42 public function flush() 43 { 44 } 45 46 public function getPrefix() 47 { 48 } 49 50 /** 51 * Retrieve multiple items from the cache by key. 52 * 53 * Items not found in the cache will have a null value. 54 * 55 * @param array $keys 56 * @return array 57 */ 58 public function many(array $keys) 59 { 60 // TODO: Implement many() method. 61 } 62 63 /** 64 * Store multiple items in the cache for a given number of minutes. 65 * 66 * @param array $values 67 * @param int $minutes 68 * @return void 69 */ 70 public function putMany(array $values, $minutes) 71 { 72 // TODO: Implement putMany() method. 73 } 74 }
5、在cache.php配置文件中添加自定义缓存store
1 /** 2 * 自定义memcache,不用memcached by winston 3 */ 4 \'memcache\' => [ 5 \'driver\' => \'memcache\', 6 \'servers\' => [ 7 [ 8 \'host\' => env(\'MEMCACHED_HOST\', \'xx.xx.xx.xx\'), 9 \'port\' => env(\'MEMCACHED_PORT\', 11211), 10 \'weight\' => 100, 11 ], 12 ], 13 ],
6、在控制器中使用
1 $val=Cache::store(\'memcache\')->get(\'xxxx\');
以上是关于laravel自定义缓存memcache(自带memcached,windows不支持)的主要内容,如果未能解决你的问题,请参考以下文章