-->

PHP资讯

您的当前位置:首页 > 资讯 > redis

php操作redis实例

2020-03-07 20:42:12  来源:admin 点击:648

话不多说,直接上代码

index.php

<?php

/**
 * redis缓存类
 * Class redisCacher
 */
class redisCacher{
    private static $cacher = null;
    protected $_redis;
    protected $_redis_ip = '127.0.0.1'; //ip
    protected $_redis_port = 6379; //端口
    protected $_redis_db = 0; //数据库号
    protected $_hash_prefix = 'zfx_'; //前缀名称

    public function __construct($ip='',$port='',$db='',$hash_prefix=''){
        if($ip != '') $this->_redis_ip = $ip;
        if($port != '') $this->_redis_port = $port;
        if($db != '') $this->_redis_db = $db;
        if($hash_prefix != '') $this->_hash_prefix = $hash_prefix;
        $this->_redis = new \Redis();
        $this->_redis->connect($this->_redis_ip, $this->_redis_port);
        $this->_redis->select($this->_redis_db);
    }
    public static function getInstance($conf){
        if(self::$cacher == null){self::$cacher = new redisCacher($conf['host'], $conf['port']);}
        return self::$cacher;
    }
    /*
     * 添加记录
     * @param $id id
     * @param $data hash数据
     * @param $hashName Hash 记录名称
     * @param $SortName Redis SortSet 记录名称
     * @param $redis Redis 对象
     * @return bool
     */
    public function set_redis_page_info($id,$data){
        if(!is_numeric($id) || !is_array($data)) return false;
        $hashName = $this->_hash_prefix.'_'.$id;
        $this->_redis->hMset($hashName, $data);
        $this->_redis->zAdd($this->_hash_prefix.'_sort',$id,$id);
        return true;
    }

    /*
     * 获取分页数据
     * @param $page 当前页数
     * @param $pageSize 每页多少条
     * @param $hashName Hash 记录名称
     * @param $SortName Redis SortSet 记录名称
     * @param $redis Redis 对象
     * @param $key 字段数组 不传为取出全部字段
     * @return array
     */
    public function get_redis_page_info($page,$pageSize,$key=array()){
        if(!is_numeric($page) || !is_numeric($pageSize)) return false;
        $limit_s = ($page-1) * $pageSize;
        $limit_e = ($limit_s + $pageSize) - 1;
        $range = $this->_redis->ZRANGE($this->_hash_prefix.'_sort',$limit_s,$limit_e);
        //指定区间内,带有 score 值(可选)的有序集成员的列表。
        $count = $this->_redis->zCard($this->_hash_prefix.'_sort'); //统计ScoreSet总数
        $pageCount = ceil($count/$pageSize); //总共多少页
        $pageList = array();
        foreach($range as $qid){
            if(count($key) > 0){
                $pageList[] = $this->_redis->hMGet($this->_hash_prefix.'_'.$qid,$key); 
                //获取hash表中所有的数据
            }else{
                $pageList[] = $this->_redis->hGetAll($this->_hash_prefix.'_'.$qid); 
                //获取hash表中所有的数据
            }
        }
        $data = array(
            'data'=>$pageList, //需求数据
            'page'=>array(
                'page'=>$page, //当前页数
                'pageSize'=>$pageSize, //每页多少条
                'count'=>$count, //记录总数
                'pageCount'=>$pageCount //总页数
            )
        );
        return $data;
    }

    /*
     * 删除记录
     * @param $id id
     * @param $hashName Hash 记录名称
     * @param $SortName Redis SortSet 记录名称
     * @param $redis Redis 对象
     * @return bool
     */
    public function del_redis_page_info($id){
        if(!is_array($id)) return false;
        foreach($id as $value){
            $hashName = $this->_hash_prefix.'_'.$value;
            $this->_redis->del($hashName);
            $this->_redis->zRem($this->_hash_prefix.'_sort',$value);
        }
        return true;
    }

    /*
     * 清空数据
     * @param string $type db:清空当前数据库 all:清空所有数据库
     * @return bool
     */
    public function clear($type='db'){
        if($type == 'db'){
            $this->_redis->flushDB();
        }elseif($type == 'all'){
            $this->_redis->flushAll();
        }else{
            return false;
        }
        return true;
    }
}
/**
 * 异常处理类
 * Class zfxException
 */
class zfxException extends Exception{
    public function __construct($message, $code = null, $previous = null){
        parent::__construct($message, $code, $previous);
    }
}

/**
 * 数据库连接处理类
 * Class db
 */
class db{
    public static  $operater;
    public $tableName;
    public $pdo;
    public $sql;
    public $pretreatment;
    public $conf;

    public function __construct($conf){
        if(empty($conf['zfxtype'])){$conf['zfxtype'] = 'mysql';}
        $this->conf = $conf;
        try{
            switch($this->conf['zfxtype']){
                case "sqlsrv":
                    $this->pdo  = new \PDO("{$conf['zfxtype']}:Server={$conf['host']},{$conf['port']};
                    Database={$conf['dbname']}", $conf['user'], $conf['pwd']);
                    break;
                case "mysql":
                    $this->pdo  = new \PDO("mysql:host={$conf['host']};port={$conf['port']};
                    dbname={$conf['dbname']}", $conf['user'], $conf['pwd']);
                    $this->pdo->query("set names {$conf['charset']}");
                    break;
            }
        }catch(Exception $e){throw new \zfxException('数据库连接失败','请检查数据库相关配置');}
    }

    public static function getInstance($conf, $tableName, $configName){
        $tableName = $conf['pre'].$tableName;
        if(empty(self::$operater[$configName])){
            self::$operater[$configName] = new db($conf);
            self::$operater[$configName]->tableName = $tableName;
            return self::$operater[$configName];
        }
        if(self::$operater[$configName]->tableName == $tableName){return self::$operater[$configName];}
        $cloner = clone self::$operater[$configName];
        $cloner->tableName = $tableName;
        return $cloner;
    }

    public function query($sql, $execute = null){
        $this->pretreatment = $this->pdo->prepare($sql);
        return $this->pretreatment->execute($execute);
    }
    public function queryFetch(){
        return $this->pretreatment->fetch(\PDO::FETCH_ASSOC);
    }

    public function queryFetchAll(){
        return $this->pretreatment->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function add($data = null){
        if(empty($data)){$data = $_POST;}
        if(!is_array($data)){throw new \zfxException('插入数据错误','插入数据应为一个一维数组');}
        $this->sql   = "insert into $this->tableName (";
        $fields      = array(); $placeHolder = array(); $insertData  = array();
        foreach ($data as $k => $v){$fields[] = "$k"; $placeHolder[] = "?"; $insertData[] = $v;}
        $this->sql .= implode(', ', $fields).') values ('.implode(', ', $placeHolder).');';
        //var_dump($this->sql);exit;
        $this->pretreatment = $this->pdo->prepare($this->sql);
        $this->pretreatment->execute($insertData);
        return $this->pdo->lastInsertId();
    }

}
/**
 * 全局配置 [可按照格式进行自定义配置]
 * @param $key1 配置名称1
 * @param $key2 配置名称2
 * @zfx
 */
function sc($key1 = null, $key2 = null){
    static $config = null;
    if($config == null){
        $config = require 'config.php';
    }
    if(is_null($key1)){return $config;}
    if(is_null($key2)){if(isset($config[$key1])){return $config[$key1];} return null;}
    if(isset($config[$key1][$key2])){return $config[$key1][$key2];}
    return null;
}
/**
 * 获取缓存方法
 * @return null
 * @throws zfxException
 * @zfx
 */
function getCacher(){
    $config = sc('cache');
    if(empty($config)){throw new zfxException('缓存设置错误');}
    $redis = redisCacher::getInstance($config);
    return $redis;
}
/**
 * 数据库连接
 * @param $tableName
 * @param string $configName
 * @return mixed
 * @zfx
 */
function db($tableName, $configName = 'db'){
    $conf = sc($configName);
    return db::getInstance($conf, $tableName, $configName);
}

/**
 * 列表
 */
//先清空一下redis
//getCacher()->clear();
$data = [];
$data = getCacher()->get_redis_page_info(4,3,array('id','subject')); //获取分页数据
//print_r($data);exit;
if(empty($data['data'])){
    //查询数据1000条,存入redis
    $data = db('board')->query('SELECT * FROM board order by idate desc');
    $arr = db('board')->queryFetchAll();
    //var_dump($arr);exit;
    foreach ($arr as $v){
        getCacher()->set_redis_page_info($v['id'],$v); //插入数据
    }
}
print_r($data);
/**
 * 插入操作
 */
//模拟数据,真实数据需接受判断一下
/*$insert_data = [
    'subject'=>'测试4',
    'author'=>'臧富祥',
    'idate'=>date('Y-m-d H:i:s'),
    'replies'=>0,
    'body'=>'测试内容',
    'ndate'=>date('Y-m-d H:i:s'),
    'ip'=>'127.0.0.1'
];
$id = db('board')->add($insert_data);
if($id){
    getCacher()->set_redis_page_info($id,$insert_data); //插入数据
}*/
?>

config.php

<?php
return array(
    // +----------------------------------------------------------------------
    // | 数据库设置
    // +----------------------------------------------------------------------
   //数据库配置默认数据库
    'db'                 => array(
        'zfxtype'      =>       'mysql',
        'host'           =>    '127.0.0.1',
        'port'           =>    '3306',
        'user'           =>    'root',
        'pwd'            =>    'root',
        'dbname'         =>    'bbs',
        'charset'        =>    'utf8',
        'pre'            =>    ''
    ),
    // +----------------------------------------------------------------------
    // | 缓存设置
    // +----------------------------------------------------------------------
   //缓存设置
   'cache'             => array(
      'type'          => 'redis',
      'pre'           => 'zfx_',
        'host'          =>'127.0.0.1',
        'port'          => '6379'
   ),
);


相关文章更多 >

© 2024版权所有 水水网

电话:171780793