1 首先在配置文件中加载
web\basic\config\web.php
........
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'zhaoyang',
],
'mecache' => [
'class' => 'yii\caching\MemCache',
'useMemcached' =>0, //这里简单说明一下 0是memcache, 1是memcached 两个是php里不同的扩展
'servers' => [
[
'host' => 'localhost',
'port' => 11211,
]
],
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
............
2 调用memcache
$mecache = Yii::$app->mecache;
$mecache->set("key","value", 60);
$mecache->get("key");
一般这么用是可以的,一点问题都没有
但是我与java 那边的memcache交出了问题
java 写的memcache,我拿不到
php 写的memcache, java拿不到
3 解决方法
web\basic\vendor\yiisoft\yii2\caching\Cache.php
//重写2个方法, 读写都调用这个方法
public function myset($key, $value, $duration = 0, $dependency = null)
{
return $this->setValue($key, $value, $duration);
}
public function myget($key)
{
return $this->getValue($key);
}
下面解释为什么这么做, 简单来讲, 程序做了加密, 去掉加密的那一层, php java 都读写统一就行了
4 分析
① $mecache = Yii::$app->mecache;
② \basic\vendor\yiisoft\yii2\caching\MemCache.php
③ class MemCache extends Cache 即成自cache \basic\vendor\yiisoft\yii2\caching\Cache.php
④ 查看原来yii2 的set 和 get 都做了加密处理
public function get($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
if ($value === false || $this->serializer === false) {
return $value;
} elseif ($this->serializer === null) {
$value = unserialize($value);
} else {
$value = call_user_func($this->serializer[1], $value);
}
if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged($this))) {
return $value[0];
} else {
return false;
}
}
public function set($key, $value, $duration = 0, $dependency = null)
{
if ($dependency !== null && $this->serializer !== false) {
$dependency->evaluateDependency($this);
}
if ($this->serializer === null) {
$value = serialize([$value, $dependency]);
} elseif ($this->serializer !== false) {
$value = call_user_func($this->serializer[0], [$value, $dependency]);
}
$key = $this->buildKey($key);
return $this->setValue($key, $value, $duration);
}
⑤ 按照上面的方法添加两个没有加密的直接读写 的memcache 问题就解决了