PHP Operations Redies Encapsulated classes

Source: Internet
Author: User
Tags empty end hash connect mysql pconnect string redis server

 -->null,//only supports a Master ' slave ' =>array (),//can have more than one slave); /** * Constructor * @param boolean $isUseCluster whether the M/s scheme/Public function __construct is used ($isUseClust
    Er=false) {$this->_isusecluster = $isUseCluster;  /** * Connect Server, NOTE: This uses long connection, improve efficiency, but will not automatically turn off * * @param array $config redis Server configuration * @param boolean $isMaster whether the currently added server is Master server * @return Boolean/Public Function connect ($config =array (' host ' => ' 127 .0.0.1 ', ' Port ' =>6379, $isMaster =true) {//default port if (!isset ($config [' Port '])} {$CONFI
        g[' port ' = 6379;
            //Set Master connection if ($isMaster) {$this->_linkhandle[' master ' = new Redis ();
        $ret = $this->_linkhandle[' master ']->pconnect ($config [' Host '], $config [' Port ']);
            }else{//Multiple Slave connections $this->_linkhandle[' Slave ' [$this->_sn] = new Redis (); $ret = $this->_linkhandle[' slave '] [$this->_sn]->pconnect ($config [' Host '], $config [' Port ']);
        + + $this->_sn;
    return $ret;
     /** * Close Connection * * @param int $flag off option 0: Close Master 1: Close Slave 2: Close all * @return Boolean
                */Public Function close ($flag =2) {switch ($flag) {//shutdown Master case 0:
            $this->getredis ()->close ();
            Break Close Slave case 1:for ($i =0; $i < $this->_sn; + + $i) {$this->_linkh
                andle[' slave ' [$i]->close ();
            } break;
                Close all Case 1: $this->getredis ()->close ();
                For ($i =0 $i < $this->_sn; + + $i) {$this->_linkhandle[' slave '] [$i]->close ();
        } break;
    return true;
 /** * Get Redis Original object can have more operations *    * @param boolean $isMaster Returns the server's type true: Returns Master false: Returns the slave of the Boolean $slaveOne returned by slave * true: Load balanced random Returns a Slave selection false: Returns all slave select * @return Redis object/Public Function Getredis ($isMaster =true, $slaveOne =t
        Rue) {///only returns Master if ($isMaster) {return $this->_linkhandle[' master ';
        }else{return $slaveOne? $this->_getslaveredis (): $this->_linkhandle[' slave ']; }/** * Write Cache * @param string $key Group Key * @param string $value Cache value * @param in T $expire expiration time, 0: No expiration/Public function set ($key, $value, $expire =0) {//Never timeout if ($expire = =
        0) {$ret = $this->getredis ()->set ($key, $value);
        }else{$ret = $this->getredis ()->setex ($key, $expire, $value);
    return $ret; /** * Read Cache * * @param string $key cache key, support multiple $key = array (' Key1 ', ' Key2 ')
     * @return String Boolean failed to return false, successful return string/Public function get ($key) {//whether to fetch multiple values at once $f UNC = Is_array ($key)?
        ' Mget ': ' Get ';
        Not using M/s if (! $this->_isusecluster) {return $this->getredis ()->{$func} ($key);
    /m/s return $this->_getslaveredis ()->{$func} ($key); /*//Magic function Public Function __call ($name, $arguments) {return Call_user_func ($name, $argum    
    Ents);
     * * */** * Conditional form cache, set if key is not saved, set failure * @param string $key Cache key * @param string $value cache value * @return Boolean/Public Function setnx ($key, $value) {return $this->getredis ()->setnx ($key
    , $value); /** * Delete Cache * * @param string array $key cache key to support a single health: "Key1" or Multiple Health: array (' Key1 ', ' key2 ') * @return int Delete the number of health/Public function remove ($key) {//$key => "Key1" Array (' Key1 ', ' Key2') return $this->getredis ()->delete ($key); /** * Value Gaga operation, similar to + + $i, if the key does not exist automatically set to 0 after the operation of Gaga * * @param string $key cache key * @param in
            The default value of T $default operation * @return the value of the int operation/Public function incr ($key, $default =1) {if ($default = 1) {
        return $this->getredis ()->incr ($key);
        }else{return $this->getredis ()->incrby ($key, $default); }/** * Value reduction operation, similar to-$i, if the key does not exist automatically set to 0 after the subtraction operation * * @param string $key cache key * @pa The default value of the RAM int $default operation * @return the value of the INT operation */Public Function decr ($key, $default =1) {if ($default =
        = 1) {return $this->getredis ()-&GT;DECR ($key);
        }else{return $this->getredis ()->decrby ($key, $default); }/** * Add empty current Database * * @return Boolean/Public Function clear () {return $ This->getredis ()->flushDB ();
     }/* =================== The following private method ===================//** * Random HASH get Redis Slave server handle * * @return Redis object/Private Function _getslaveredis () {//Directly returns if ($this on a single Slave machine)
        -&GT;_SN <= 1) {return $this->_linkhandle[' slave '][0];
        }//random Hash gets Slave handle $hash = $this->_hashid (Mt_rand (), $this->_sn);
    return $this->_linkhandle[' slave ' [$hash];
     /** * Gets the value of the hash after 0~m-1 based on ID * * @param string $id * @param int $m * @return int
        /Private Function _hashid ($id, $m =10) {//Converts the string k to a value between 0~m-1 as the hash address of the corresponding record $k = MD5 ($id);
        $l = strlen ($k);
        $b = Bin2Hex ($k);
        $h = 0;
        For ($i =0 $i < $l; $i + +) {//additive pattern hash $h + = substr ($b, $i *2,2);
        $hash = ($h *1)% $m;
    return $hash;
   }/** * Lpush * Public Function Lpush ($key, $value) {return $this->getredis ()->lpush ($key, $value);
    }/** * Add Lpop */Public Function Lpop ($key) {return $this->getredis ()->lpop ($key); }/** * Lrange/Public Function Lrange ($key, $start, $end) {return $this->getredis ()->    
    Lrange ($key, $start, $end);
            }/** * Set hash opeation */Public Function Hset ($name, $key, $value) {if (Is_array ($value)) {    
        return $this->getredis ()->hset ($name, $key, serialize ($value));
    return $this->getredis ()->hset ($name, $key, $value); }/** * Get hash opeation */Public Function hget ($name, $key = null, $serialize =true) {if ($key
            {$row = $this->getredis ()->hget ($name, $key);
            if ($row && $serialize) {unserialize ($row);
        return $row; Return $this->getredis ()->hgetall ($name);
            }/** * Delete hash opeation */Public Function Hdel ($name, $key = null) {if ($key) {
        return $this->getredis ()->hdel ($name, $key);
    return $this->getredis ()->hdel ($name);    
    }/** * Transaction start/Public Function multi () {return $this->getredis ()->multi (); /** * Transaction Send/Public function exec () {return $this->getredis ()->exec    
    (); }//End Class//================= TEST DEMO =================//Only one Redis application $redis = new
Rediscluster ();


$redis->connect (Array (' Host ' => ' 127.0.0.1 ', ' Port ' =>6379));
* $cron _id = 10001; $CRON _key = ' cron_list ';
$PHONE _key = ' phone_list: '. $cron _id;////cron Info $cron = $redis->hget ($CRON _key, $cron _id); if (empty ($cron)) {$cron = array (' ID ' =>10, ' name ' => ' Jackluo ');//mysql data $redis->hset ($Cron_key, $cron _id, $cron);
Set Redis}//phone list $phone _list = $redis->lrange ($PHONE _key,0,-1);
Print_r ($phone _list);    if (Empty ($phone _list)) {$phone _list =explode (', ', ' 13228191831,18608041585 ');
        MySQL Data//join list if ($phone _list) {$redis->multi ();            
        foreach ($phone _list as $phone) {$redis->lpush ($PHONE _key, $phone);
    } $redis->exec ();


} print_r ($phone _list);

/* $list = $redis->hget ($cron _list,);

Var_dump ($list); *///*///$redis->set (' id ', 35);
    /* $redis->lpush (' Test ', ' 1111 ');
    $redis->lpush (' Test ', ' 2222 ');

    $redis->lpush (' Test ', ' 3333 ');
    $list = $redis->lrange (' Test ', 0,-1);
    Print_r ($list);
    $lpop = $redis->lpop (' Test ');
    Print_r ($lpop);
    $lpop = $redis->lpop (' Test ');
    Print_r ($lpop);
    $lpop = $redis->lpop (' Test ');
Print_r ($lpop); *///Var_dump ($redis->get (' id '));




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.