77103@DESKTOP-C2JB47R MINGW64 /e/dev/basic
$ ./yii
This is Yii version 2.0.15.1.
The following commands are available:
配置文件
'components' => [
//数据缓存到memcache
'cache' => [
'class' => 'yiicachingMemCache',
'servers' => [
[
'host' => 'localhost',
'port' => 11211,
'weight' => 100,
]
],
],
<?php
namespace app\controllers;
use yii\web\Controller;
use Yii;
class TestController extends Controller
{
public function actionIndex()
{
$key = 'people';
$value = json_encode(array('name'=>'ball', 'age'=>'male'));
$expire = 60000;
yii::$app->cache->set($key, $value,$expire);
$data =Yii::$app->cache->get($key);
\Logic::vd($data);
}
}
// 结果:bool(false)
<?php
namespace app\controllers;
use yii\web\Controller;
use Yii;
class TestController extends Controller
{
public function actionIndex()
{
$key = 'people';
$value = json_encode(array('name'=>'ball', 'age'=>'male'));
$expire = 60000;
yii::$app->cache->set($key, $value);
$data =Yii::$app->cache->get($key);
\Logic::vd($data);
}
}
//结果:string(28) "{"name":"ball","age":"male"}"
Yii::$app->cache->set('key','value');
,当这句话没有设置有效时间为多少秒时,可以正常获取到缓存中键为key的值,但表示此key不过期。Yii::$app->cache->set('key','value',60);
比如60秒,就会出现取不到key对应的value值,网上和论坛里搜了搜,没有找到解决办法,也有很多phper遇到这类似的问题。所以特意去看了看底层代码,引用的memcache类为Yii2自带的yii\caching\MemCache,Yii::$app->cache->set('key','value');
这句代码会自动调用memcache类下的setValue方法来设置缓存,所以问题也许就出现在这儿了。return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire)
的问题,将这句代码改为return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $duration)
后, 再测试发现问题已经解决。