标签:php扩展 二次 map self field 差距 his 4.0 sele
首先要确保有Redis的服务
# redis-cli -v
redis-cli 3.2.8
# redis-server -v
Redis server v=3.2.8 sha=00000000:0 malloc=jemalloc-4.0.3 bits=64 build=e034df79550b120
然后确保PHP已经添加了Redis扩展
# php -m |grep redis
redis
然后要创建Redis类
<?php
class Red {
static private $redis = NULL;
private $_red = NULL;
private $_return_data = NULL;
static public function create() {
if(self::$redis) {
return Red::$redis;
}
self::$redis = new self;
return self::$redis;
}
public function __call($func, $params) {
if ($func == 'multi') {
$this->_return_data = $this->_red->multi($params[0]);
} else {
$this->_return_data = call_user_func_array(array(&$this->_red, $func), $params);
}
return $this->_return_data;
}
private function __construct() {
$this->_red = new Redis();
$this->_red->connect(C("REDIS_HOST"),C("REDIS_PORT"));
$this->_red->select(C('REDIS_DB') ?: 0);
return Red::$redis;
}
}
config.php中配置Redis
'REDIS_HOST' => '127.0.0.1',
'REDIS_PROT' => 6379,
使用Redis,可以提高查询速度,一些不变的查询,可以保存到Redis中,进行快速查询。比如查询城市信息,保存到Redis中,不必每次都查看数据库。
// 获取区域数据
public function get_map() {
vendor('Redis.Red');
$redis = Red::create();
$data = $redis->get('china:area');
if (!$data) {
$areaModel = M('china_area');
$p = $areaModel->field('id,name,level')->where(['level' => 1])->select();
foreach ($p as $k => $v) {
$c = $areaModel->field('id,name,level')->where(['level' => 2, 'upid' => $v['id']])->select();
foreach ($c as $ck => $cv) {
$p[$k]['child'][$ck] = $cv;
$d = $areaModel->field('id,name,level')->where(['level' => 3, 'upid' => $cv['id']])->select();
foreach ($d as $dk => $dv) {
$p[$k]['child'][$ck]['child'][] = $dv;
}
}
}
$redis->set('china:area', json_encode($p,JSON_UNESCAPED_UNICODE));
} else {
$p = json_decode($data, true);
}
$this->json->setAttr("data", $p);
$this->json->Send();
}
第一次查询,用时
第二次查询,已经存入Redis
差距很明显吧!!!
Redis一个key或value值可以存储512M的数据,很强大了。
可以去redis中查看一下,
127.0.0.1:6379> keys china:area
1) "china:area"
Redis 可以存储任意类型的数据,最好通过json加密进去吧。获取的时候,进行解密。
查看PHP扩展文档,https://github.com/phpredis/phpredis/
标签:php扩展 二次 map self field 差距 his 4.0 sele
原文地址:https://www.cnblogs.com/jiqing9006/p/9092933.html