Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。他的数据读取速度要比查询mysql等硬盘级的速度快的多,所以我们尝试用redis做数据分页。

首先写一个用来链接redis及操作的类:


class RedisListBase
{

    public $connect;

    function __construct($db_ip='127.0.0.1', $db_port=6379, $password='', $library=4)
    {
        $this->connect = new Redis();
        $this->connect->connect($db_ip, $db_port);
        if($password) $this->connect->auth($password); //密码验证
        if($library) $this->connect->select($library); //选择库
    }

    /**
     * @description: Hash存储
     * @author: injurys
     * @param string $tableName  存储表名
     * @param array $info  存储数据
     * @return bool|int
     */
    function pushHashData($tableName='table', $info=[]){
        $data = [];
        foreach ($info as $k => $v){
            $data[$k] = json_encode($v, JSON_UNESCAPED_SLASHES);
        }
        return $this->connect->hMset($tableName, $data);
    }


    /**
     * @description: 移除Zset指定数据
     * @author: injurys
     * @param string $tableName 存储表名
     * @param string|array $value 内容
     *                     字符串 删除单个 'key1'
     *                     数组  删除多个 ['key1', 'key2']
     * @return int
     */
    function delZsetData($tableName='table', $value='')
    {
        if(is_array($value)){
            foreach ($value as $k){
                $this->connect->zRem($tableName, $k);
            }
            return 1;
        }else{
            return $this->connect->zRem($tableName, $value);
        }
    }

    /**
     * @description: 删除Hash数据
     * @author: injurys
     * @param string $tableName  存储表名
     * @param string $key 删除的键 (为空删除所有)
     * @return bool|int
     */
    function hDel($tableName='table', $key='')
    {
        if(empty($key)){
            $name = $this->connect->hGetAll($tableName);
            if($name){
                foreach ($name as $k => $n){
                    $this->connect->hDel($tableName, $k);
                }
            }
            return 1;
        }else{
            return $this->connect->hDel($tableName, $key);
        }
    }

    /**
     * @description: Hash读取
     * @author: injurys
     * @param string $tableName  存储表名
     * @param string $name   存储键名
     *                          为空:取出所有
     *                          数组:取出多个
     *                          字符串:取出单个
     * @return array|string
     */
    function getHashData($tableName='table', $name='')
    {
        $data = [];
        $res = [];
        if(empty($name)){
            $data = $this->connect->hGetAll($tableName);
        }else{
            if(is_array($name))
                $data = $this->connect->hMget($tableName, $name);
            else
                $res = $this->connect->hGet($tableName, $name);
        }
        if($data){
            foreach ($data as $k => $v){
                if($v){
                    $res[$k] = json_decode($v, true);
                }
            }
        }
        return $res;
    }

}

然后写用于新增、删除、查询的类并继承刚才的基础类:


class RedisList extends RedisListBase
{

    public $dbName = 'list_data';
    public $dbNameSort = 'list_data_sort';

    /**
     * @description: 添加纪录
     * @author: injurys
     * @param int $id  记录ID
     * @param array $data 数据详情
     * @return bool
     */
    public function addDataBase($id, $data=[])
    {
        if(empty($id) || empty($data) || !is_array($data)) return false;
        $this->pushHashData($this->dbName.'_'.$id, $data);
        $this->connect->zAdd($this->dbNameSort, $id, $id);
        return true;
    }


    /**
     * @description: 删除一条数据
     * @author: injurys
     * @param int $id 主键ID
     * @return bool
     */
    public function delDataBase($id=0)
    {
        if(empty($id)) return false;
        $this->hDel($this->dbName.'_'.$id);
        $this->delZsetData($this->dbNameSort, $id);
        return true;
    }

    /**
     * @description: 获取列表
     * @author: injurys
     * @param int $page
     * @param int $pageSize
     * @param array $field
     * @param string $sort
     * @return array
     */
    public function getPageList($page=1, $pageSize=20, $field=[],$sort='asc')
    {
        if(!is_numeric($page) || !is_numeric($pageSize)) return [];
        $pageSize = ($pageSize < 1 || $pageSize > 100) ? 20 : $pageSize;
        $limitStart = ($page-1) * $pageSize;       //查询开始索引
        $limitEnd = $limitStart + $pageSize - 1;   //查询结束索引
        if ($sort=='asc')
            $range = $this->connect->zRange($this->dbNameSort, $limitStart, $limitEnd);
        else
            $range = $this->connect->zRevRange($this->dbNameSort, $limitStart, $limitEnd);

        $count = $this->connect->zCard($this->dbNameSort);
        $pageCount = ceil($count / $pageSize); //总共多少页
        $pageList = [];
        foreach($range as $id){
            $pageList[] = $this->getHashData($this->dbName.'_'.$id, $field);
        }
        $data = [
            'list' => $pageList,
            'count' => $count,
            'pageCount' => $pageCount,
        ];
        return $data;
    }

}

然后我们就可以进行使用了:

$listBase = new RedisList();

1、数据入库

这里我们用循环模拟数据入缓存,内容字段用随机字符串:

foreach ([1,2,3,4,5,6,7,8,9,10] as $id){
    $data = [
        'id' => $id,
        'name' => 'name_'.$id.'_'.uniqid(),
        'age' => 'age_'.$id.'_'.uniqid(),
    ];
    $listBase->addDataBase($id, $data);
}

2、删除数据操作

根据ID直接进行删除。

$listBase->delDataBase(10);

3、数据查询

参数:getPageList(page, size, field, order);

> page    查询的页码  
> size    每页的数据调数  
> field   要查询的字段  
> order   排序 支持 'asc'、 `desc`  

$list = $listBase->getPageList(1,3,['id', 'name'], 'desc');

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!