分享按钮

php +Redis

默认分类 / 2764人浏览 / 0人评论
<?php
/**
* Created by PhpStorm.
* User: Author: 青衫&故人 <164934547@qq.com>
* Date: 2021/2/6
* Time: 14:38
*/

namespace app\common\library;


class Redis
{
   public  $redis="";

   /**
    * 定义单例模式变量
    * */
   private static $_instance=null;
   protected $optionsarray;

   public static function getInstance(){
       if(empty(self::$_instance)){
           self::$_instance=new self();
       }
       return self::$_instance;
   }


   private function __construct($options=[])
   {
       try{
           $this->optionsarray=[
               'host' =>config('redis')['host']?:'127.0.0.1',
               'port' =>config('redis')['port']?:6379,
               'password' =>config('redis')['password']?:'',
               'select' => 0,
               'timeout' =>config('redis')['timeout']?:65,//超时时间
               'expire' =>0,//过期时间
               'persistent' => false,//是否持久化
               'prefix' => config('redis')['prefix']?:'',//前缀
           ];

           # 判断是否有扩展(如果你的apachereids扩展就会抛出这个异常)
           if (!extension_loaded('redis')) {
               throw new \BadFunctionCallException('not support: redis');
           }
           if (!empty($options)) {
               $this->optionsarray = array_merge($this->optionsarray, $options);
           }
           $func = $this->optionsarray['persistent'] ? 'pconnect' : 'connect';     //判断是否长连接
           $this->redis = new \Redis();        // 实例化
           $result=$this->redis->$func($this->optionsarray['host'], $this->optionsarray['port'], $this->optionsarray['timeout']);
           if ('' != $this->optionsarray['password']) {
               $this->redis->auth($this->optionsarray['password']);
           }
           if (0 != $this->optionsarray['select']) {
               $this->redis->select($this->optionsarray['select']);
           }
           if($result===false){
               throw  new \Exception("Redis connect error");
           }
       }catch (\RedisException $exception){

           echo 'Redis is not on ';exit;
       }

   }


   /**
    * 写入key-value
    * @param $key string 要存储的key
    * @param $value mixed 要存储的值
    * @param $type int 写入方式 0:不添加到现有值后面 1:添加到现有值的后面 默认0
    * @param $repeat int 0:不判断重复 1:判断重复
    * @param $time float 过期时间(S)
    * @param $old int 1:返回旧的value 默认0
    * @return $return bool true:成功 flase:失败
    */
   public  function Set($key,$value,$type=0,$repeat=0,$time=0,$old=0)
   {
       $return = null;
       if ($type) {
           $return = $this->redis->append($key, $value);
       } else {
           if ($old) {
               $return = $this->redis->getSet($key, $value);
           } else {
               if ($repeat) {
                   $return = $this->redis->setnx($key, $value);
               } else {
                   if ($time && is_numeric($time)) $return = $this->redis->setex($key, $time, $value);
                   else $return = $this->redis->set($key, $value);
               }
           }
       }

       return $return;
   }


   /**
    * 获取某个key值 如果指定了start end 则返回key值的startend之间的字符
    * @param $key string/array 要获取的key或者key数组
    * @param $start int 字符串开始index
    * @param $end int 字符串结束index
    * @return $return mixed 如果key存在则返回key值 如果不存在返回false
    */
   public  function Get($key=null,$start=null,$end=null)
   {
       $return = null;
       if (is_array($key) && !empty($key)) {
           $return =$this->redis->getMultiple($key);
       } else {
           if (isset($start) && isset($end)) $return =$this->redis->getRange($key);
           else $return = $this->redis->get($key);
       }

       return $return;
   }

   /**
    * 获取满足给定pattern的所有key
    * @param $key regexp key匹配表达式 模式:user* 匹配以user开始的key
    */
   public   function GetKeys($key=null)
   {
       $return = null;

       $return = $this->redis->keys($key);

       return $return;
   }

   /**
    * 删除某个key
    * @param $key array key数组
    * @return $return longint 删除成功的key的个数
    */
   public   function Deletes($key=array())
   {
       $return = null;

       $return = $this->redis->del($key);

       return $return;
   }





   /**
    *
    * value写入set集合 如果value存在 不写入 返回false
    * 如果是有序集合则根据score值更新该元素的顺序
    * @param $set string 集合名
    * @param $value mixed
    * @param $stype int 集合类型 0:无序集合 1:有序集和 默认0
    * @param $score int 元素排序值
    */
   public   function SetAdd($set,$value=null,$stype=0,$score=null)
   {
       $return = null;

       if ($stype && $score !== null) {
           $return = $this->redis->zAdd($set, $score, $value);
       } else {

           $return = $this->redis->sAdd($set, $value);
       }

       return $return;
   }

   /**
    * 移除set1中的value元素 如果指定了set2 则将该元素写入set2
    * @param $set1 string 集合名
    * @param $value mixed
    * @param $stype int 集合类型 0:无序集合 1:有序集和 默认0
    * @param $set2 string 集合名
    */
   public   function SetMove($set1, $value=null, $stype=0, $set2=null)
   {
       $return = null;

       if ($set2) {
           $return =$this->redis->sMove($set1, $set2, $value);
       } else {
           if ($stype) $return = $this->redis->zRem($set1, $value);
           else $return = $this->redis->sRem($set1, $value);
       }

       return $return;
   }



   /**
    * 返回set中所有元素个数 有序集合要指定$stype=1
    * 如果是有序集合并指定了$start$end 则返回scorestartend之间的元素个数
    * @param $set string 集合名
    * @param $stype int 集合类型 0:无序集合 1:有序集和 默认0
    * @param $start int 开始index
    * @param $end int 结束index
    */
   public   function SetSize($set,$stype=0,$start=0,$end=0)
   {
       $return = null;
       if ($stype) {
           if ($start && $end) $return = $this->redis->zCount($set, $start, $end);
           else $return = $this->redis->zSize($set);
       } else {
           $return = $this->redis->sSize($set);
       }
       return $return;
   }



   /**
    * 随机返回set中一个元素并可选是否删除该元素
    * @param $set string 集合名
    * @param $isdel int 是否删除该元素 0:不删除 1:删除 默认为0
    */
   public  function SetPop($set,$isdel=0)
   {
       $return = null;

       if ($isdel) {
           $return = $this->redis->sPop($set);
       } else {
           $return =$this->redis->sRandMember($set);
       }

       return $return;
   }




   /**
    * 返回set中所有元素
    * @param $set string 集合名
    */
   public   function SetMembers($set)
   {
       $return = null;

       $return = $this->redis->sMembers($set);

       return $return;
   }

   /**
    * ***只针对有序集合操作
    * 返回setindexstartend的所有元素
    * @param $set string 集合名
    * @param $start int 开始Index
    * @param $end int 结束Index
    * @param $order int 排序方式 0:从小到大排序 1:从大到小排序 默认0
    * @param $score bool 元素排序值 false:返回数据不带score true:返回数据带score 默认false
    */
   public  function SetRange($set,$start,$end,$order=0,$score=false)
   {
       $return = null;
       if ($order) {
           $return = $this->redis->zRevRange($set, $start, $end, $score);
       } else {
           $return =$this->redis->zRange($set, $start, $end, $score);
       }
       return $return;
   }


   /**
    * ***只针对有序集合操作
    * 删除setscorestartend的所有元素
    * @param $set string 集合名
    * @param $start int 开始score
    * @param $end int 结束score
    */
   public    function SetDeleteRange($set,$start,$end)
   {
       $return = null;

       $return =$this->redis->zRemRangeByScore($set, $start, $end);

       return $return;
   }

   /**
    * ***只针对有序集合操作
    * 获取set中某个元素的score
    * 如果指定了inc参数 则给该元素的score增加inc
    * 如果没有该元素 则将该元素写入集合
    * @param $set string 集合名
    * @param $value mixed 元素值
    * @param $inc int 要给score增加的数值 默认是null 不执行score增加操作
    */
   public  function SetScore($set,$value,$inc=null)
   {
       $return = null;

       if ($inc) {
           $return = $this->redis->zIncrBy($set, $inc, $value);
       } else {
           $return =$this->redis->zScore($set, $value);
       }

       return $return;
   }


   /**
    * key->value写入hash表中
    * @param $hash string 哈希表名
    * @param $data array 要写入的数据 array('key'=>'value')
    */
   public  function HashSet($hash,$data,$keystr)
   {
       $return = null;
       if (is_array($data) && !empty($data)) {
         

           $return =$this->redis->hMset($hash, $data);
       }
       return $return;
   }



   /**
    * 获取hash表的数据
    * @param $hash string 哈希表名
    * @param $key mixed 表中要存储的key名 默认为null 返回所有key>value
    * @param $type int 要获取的数据类型 0:返回所有key 1:返回所有value 2:返回所有key->value
    */
   public  function HashGet($hash,$key=array(),$type=0)
   {
       $return = null;

       if ($key) {
           if (is_array($key) && !empty($key))
           {

               $return = $this->redis->hMGet($hash,$key);
           }
           else
           {

               $return =$this->redis->hGet($hash,$key);
           }
       } else {
           switch ($type) {
               case 0:
                   $return =$this->redis->hKeys($hash);
                   break;
               case 1:
                   $return = $this->redis->hVals($hash);
                   break;
               case 2:
                   $return = $this->redis->hGetAll($hash);
                   break;
               default:
                   $return = false;
                   break;
           }
       }
       return $return;
   }



   /**
    * 获取分页数据
    * @param $hash_prefix 前缀
    * @param $page 当前页数
    * @param $pageSize 每页多少条
    * @param $hashName Hash 记录名称
    * @param $SortName Redis SortSet 记录名称
    * @param $redis Redis 对象
    * @param $key 字段数组 不传为取出全部字段
    * @return array
    */
   public function get_redis_page_info($hash_prefix,$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($hash_prefix,$limit_s,$limit_e); //指定区间内,带有 score (可选)的有序集成员的列表。
       $count = $this->redis->zcard($hash_prefix); //统计ScoreSet总数
       $pageCount = ceil($count/$pageSize); //总共多少页
       $pageList = array();

       foreach($range as $qid){
           if(count($key) > 0){
               $pageList[] =$this->redis->hMGet($hash_prefix.'_'.$qid,$key); //获取hash表中所有的数据
           }else{
               $pageList[] = $this->redis->hGetAll($hash_prefix.'_'.$qid); //获取hash表中所有的数据
           }
       }
       $data = array(
           'data'=>$pageList, //需求数据
           'page'=>array(
               'page'=>$page, //当前页数
               'pageSize'=>$pageSize, //每页多少条
               'count'=>$count, //记录总数
               'pageCount'=>$pageCount //总页数
           )
       );
       return $data;
   }



   /**
    * 查询hash表中某个key是否存在
    * @param $hash string 哈希表名
    * @param $key mixed 表中存储的key
    */
   public  function HashExists($hash,$key)
   {
       $return = null;

       $return =$this->redis->hExists($hash,$key);

       return $return;
   }


   /**
    * 自增hash表中某个key的值
    * @param $hash string 哈希表名
    * @param $key mixed 表中存储的key
    * @param $inc int 要增加的值
    */
   public   function HashInc($hash,$key,$inc)
   {
       $return = null;

       $return =$this->redis->hIncrBy($hash, $key, $inc);

       return $return;
   }


   /**
    * 设置key过期时间
    * @param $key
    * @param $time mixed 时间秒
    * @return  true
    */
   public  function SetKeyExpire($key, $time)
   {
       $return = null;

       $return =self::$handler->setTimeout($key, $time);

       return $return;
   }


   /**
    * 获取hash表中元素个数
    * @param $hash string 哈希表名
    */
   public  function HashLen($hash)
   {
       $return = null;

       $return =$this->redis->hLen($hash);

       return $return;
   }

   /**
    * 删除hash表中的key
    * @param $hash string 哈希表名
    * @param $key mixed 表中存储的key
    */
   public  function HashDel($hash,$key)
   {
       $return = null;



       $return = $this->redis->hDel($hash,$key);

       return $return;
   }

   /**
    * 删除hash表中的key
    * @param $hash string 哈希表名
    */
   public  function HashAllDel($hash)
   {
       $return = null;

       $return = $this->redis->Del($hash);

       return $return;
   }


   /**
    * 获取值长度
    * @param string $key
    * @return int
    */
   public  function lLen($key)
   {
       return $this->redis->lLen($key);
   }



   /**
   描述: 添加一个集合。
   参数:key value
   返回值:成功返回指定元素的值,失败false
    */
   public  function SAdd($key,$value)
   {
       return self::$handler->sAdd($key, $value);
   }

   /**
    * 获取数量
    *
    * */
   public function  SCard($key){

     return  $this->redis->sCard($key);

   }


   /**
    * 获取上次成功将数据保存到磁盘的Unix时戳
    */
   public  function LastSave()
   {
       $return = null;

       $return =$this->redis->lastSave();

       return $return;
   }



   /**
    * 求交集 并可选是否将交集保存到新集合
    * @param $set array 集合名数组
    * @param $newset string 要保存到的集合名 默认为null 即不保存交集到新集合
    * @param $stype int 集合类型 0:无序集合 1:有序集和 默认0
    * @param $weight array 权重 执行function操作时要指定的每个集合的相同元素所占的权重 默认1
    * @param $function string 不同集合的相同元素的取值规则函数 SUM:取元素值的和 MAX:取最大值元素 MIN:取最小值元素
    */
   public  function SetInter($set,$newset=null,$stype=0,$weight=array(1),$function='SUM')
   {
       $return = array();

       if (is_array($set) && !empty($set)) {
           if ($newset) {
               if ($stype) $return =$this->redis->zInter($newset, $set, $weight, $function);
               else $return = $this->redis->sInterStore($newset, $set);
           } else {
               $return = $this->redis->sInter($set);
           }
       }

       return $return;
   }




   /**
    * 求并集 并可选是否将交集保存到新集合
    * @param $set array 集合名数组
    * @param $newset string 要保存到的集合名 默认为null 即不保存交集到新集合
    * @param $stype int 集合类型 0:无序集合 1:有序集和 默认0
    * @param $weight array 权重 执行function操作时要指定的每个集合的相同元素所占的权重 默认1
    * @param $function string 不同集合的相同元素的取值规则函数 SUM:取元素值的和 MAX:取最大值元素 MIN:取最小值元素
    */
   public   function SetUnion($set,$newset=null,$stype=0,$weight=array(1),$function='SUM')
   {
       $return = array();

       if (is_array($set) && !empty($set)) {
           if ($newset) {
               if ($stype) $return = $this->redis->zUnion($newset, $set, $weight, $function);
               else $return = $this->redis->sUnionStore($newset, $set);
           } else {
               $return = $this->redis->sUnion($set);
           }
       }

       return $return;
   }


   /**
    * 求差集 并可选是否将交集保存到新集合
    * @param $set array 集合名数组
    * @param $newset string 要保存到的集合名 默认为null 即不保存交集到新集合
    */
   public  function SetDiff($set,$newset=null)
   {
       $return = array();

       if (is_array($set) && !empty($set)) {
           if ($newset) {
               $return = $this->redis->sDiffStore($newset, $set);
           } else {
               $return =  $this->redis->sDiff($set);
           }
       }
       return $return;
   }



   /**
    * 获取redis版本信息等详情
    */
   public  function Info()
   {
       $return = null;

       $return = $this->redis->info();

       return $return;
   }


   /**
    * 获取数据库中key的数目
    */
   public   function dbSize()
   {
       $return = null;

       $return =$this->redis->dbSize();

       return $return;
   }


   /**
    *
    * 清空所有的数据
    **/
   public function DellAll()
   {
       return  $this->redis->flushall();
   }



}


感谢博主,喝杯咖啡~