laravel自带memcached没有win版,memcache又没定义
踩过这个坑,所以从其他地方转了这篇文章
1、首先弄清楚memcache和memcached的区别(小白谈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配置文件添加提供者注册
namespace App\Providers;
use Cache;
use App\Extensions\MemcacheStore;
use Illuminate\Support\ServiceProvider;
class MemcacheServiceProvider extends ServiceProvider
{
public function boot()
{
Cache::extend(‘memcache‘, function ($app) {
return Cache::repository(new MemcacheStore($app[‘memcache.connector‘]));
});
}
public function register()
{
//注册memcache连接的单例
$this->app->singleton(‘memcache.connector‘, function ($app) {
$config = $app[‘config‘]["cache.stores.memcache"];
$servers = $config[‘servers‘][0];
return memcache_connect($servers[‘host‘], $servers[‘port‘]);
});
}
}
//app.php
<?php
return [
'providers' => [
//......
App\Providers\MemcacheServiceProvider::class,
]
]
4、完善存储类MemcacheStore(可在app添加Extensions文件夹存放)
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/2
* Time: 9:58
*/
namespace App\Extensions;
class MemcacheStore implements \Illuminate\Contracts\Cache\Store
{
//memcache资源
protected $memcache_conn;
public function __construct($conn)
{
$this->memcache_conn=$conn;
}
public function __destruct()
{
// TODO: Implement __destruct() method.
$this->memcache_conn=null;//释放资源
}
public function get($key)
{
return $this->memcache_conn->get($key);
}
public function put($key, $value, $minutes)
{
return $this->memcache_conn->set($key, $value,0, $minutes);
}
public function increment($key, $value = 1)
{
}
public function decrement($key, $value = 1)
{
}
public function forever($key, $value)
{
}
public function forget($key)
{
}
public function flush()
{
}
public function getPrefix()
{
}
/**
* Retrieve multiple items from the cache by key.
*
* Items not found in the cache will have a null value.
*
* @param array $keys
* @return array
*/
public function many(array $keys)
{
// TODO: Implement many() method.
}
/**
* Store multiple items in the cache for a given number of minutes.
*
* @param array $values
* @param int $minutes
* @return void
*/
public function putMany(array $values, $minutes)
{
// TODO: Implement putMany() method.
}
}
5、在cache.php配置文件中添加自定义缓存store
/**
* 自定义memcache,不用memcached by winston
*/
'memcache' => [
'driver' => 'memcache',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
6、在控制器中使用
Cache::store('memcache')->put('test-put','test-put',60);
Cache::store('memcache')->set('test-set','test-set',60);
Cache::store('memcache')->get('test-put');//test-put
Cache::store('memcache')->get('test-set');//test-set
转载地址:laravel自定义缓存memcache(自带memcached,windows不支持) - winstonsias - 博客园