PHP Redis Database Operation class

Source: Internet
Author: User
Tags auth delete key explode php redis

<?phpnamespace Iphp\db;use iphp\app;/** * Redis Operation class * Description, any string that is false, there are empty strings in Redis. * Returns false only if key does not exist. * This can be used to prevent cache penetration * @author Xuen * */class redis{private $redis;//Current database ID protected $dbId =0;//current Authorization code protected $auth;/** * instantiation The object, Singleton mode. * @var \iphp\db\redis */static private $_instance=array ();p rivate $k;//Connection property array protected $attr =array (//connection time-out, Redis configuration file    The default is 300 seconds ' timeout ' =>30,//Select the database.        ' db_id ' =>0,);//When to reestablish the connection protected $expireTime;        protected $host;        protected $port;    Private Function __construct ($config, $attr =array ()) {$this->attr=array_merge ($this->attr, $attr);    $this->redis=new \redis ();    $this->port= $config [' Port ']? $config [' Port ']:6379;    $this->host= $config [' Host '];        $this->redis->connect ($this->host, $this->port, $this->attr[' timeout ');        if ($config [' auth ']) {$this->auth ($config [' auth ']);    $this->auth= $config [' auth ']; } $this->expiretime=time () + $this->attr[' timeout ';} /** * Gets the instantiated object. * Establish a connection for each database * If the connection times out, a connection will be re-established * @param array $config * @param int $dbId * @return \iphp\db\redis */public static func tion getinstance ($config, $attr =array ()) {//If it is a string, it is considered to be the ID number of the database.    To simplify the wording.        if (!is_array ($attr)) {$dbId = $attr;        $attr =array ();    $attr [' db_id ']= $dbId; } $attr [' db_id ']= $attr [' db_id ']? $attr [' db_id ']:0;if (!is_array ($config)) $config =app::getapp ()->getconfig ($con    FIG);    $k =md5 (Implode (", $config). $attr [' db_id ']); if (!    (static::$_instance[$k] instanceof self))        {//static::$_instance[$k]->close ();        static::$_instance[$k] = new self ($config, $attr);        static::$_instance[$k]->k= $k;                static::$_instance[$k]->dbid= $attr [' db_id '];        If it is not library No. 0, select the database.    if ($attr [' db_id ']!=0) static::$_instance[$k]->select ($attr [' db_id ']);    } ElseIf (Time () >static::$_instance[$k]->expiretime) {static::$_instance[$k]->close ();    static::$_instance[$k] = new self ($config, $attr);        static::$_instance[$k]->k= $k;                 static::$_instance[$k]->dbid= $attr [' db_id '];        If it is not library No. 0, select the database.    if ($attr [' db_id ']!=0) static::$_instance[$k]->select ($attr [' db_id ']); } return static::$_instance[$k];} Private Function __clone () {}/** * performs native Redis operation * @return \redis */public function Getredis () {return $this->redis;} /*****************hash table Operation function *******************//** * Get the value of a field in the hash table * @param string $key Cache key * @param string $field field * @return String|false */public function Hget ($key, $field) {return $this->redis->hget ($key, $field);} /** * Set the value of a field for the hash table * @param string $key Cache key * @param string $field field * @param string $value value. * @return bool */public function Hset ($key, $field, $value) {return $this->redis->hset ($key, $field, $value);} /** * Determine the hash table, specify whether field is present * @param string $key Cache key * @param string $field field * @return bool */public functionHexists ($key, $field) {return $this->redis->hexists ($key, $field);} /** * Delete the specified field in the hash table, support bulk Delete * @param string $key Cache key * @param string $field field * @return int */public function Hdel ($key        , $field) {$fieldArr =explode (', ', $field);        $delNum = 0;            foreach ($fieldArr as $row) {$row =trim ($row);        $delNum + = $this->redis->hdel ($key, $row); } return $delNum;} /** * Returns the number of hash table elements * @param string $key cache key * @return Int|bool */public function Hlen ($key) {return $this->redis->hl En ($key);} /** * Sets the value of a field for the hash table, returns False if the field exists @param string $key cache key * @param string $field field * @param string $value value. * @return bool */public function hsetnx ($key, $field, $value) {return $this->redis->hsetnx ($key, $field, $value);} /** * Set values for multiple fields of the hash table. * @param string $key * @param array $value * @return array|bool */public function Hmset ($key, $value) {if (!is_array ($val    UE)) return false; return $this->redis->hmset ($key, $value);}/** * Set values for multiple fields of the hash table. * @param string $key * @param array|string $value string with ', ' separator field * @return Array|bool */public function Hmget ($key, $field    {if (!is_array ($field)) $field =explode (', ', $field); return $this->redis->hmget ($key, $field);} /** * For hash table Set this additive, can be negative * @param string $key * @param int $field * @param string $value * @return bool */public function hIn Crby ($key, $field, $value) {$value =intval ($value), return $this->redis->hincrby ($key, $field, $value);} /** * Returns all fields of all hash tables * @param string $key * @return array|bool */public function Hkeys ($key) {return $this-&GT;REDIS-&GT;HK Eys ($key);} /** * Returns the field value of all hash tables as an indexed array * @param string $key * @return array|bool */public function hvals ($key) {return $this->redis ->hvals ($key);} /** * Returns the field value of all hash tables as an associative array * @param string $key * @return array|bool */public function Hgetall ($key) {return $this->red Is->hgetall ($key);} /********************* an ordered set operation *********************//** * Adds an element to the current collection * If value already exists, the value of order is updated. * @param string $key * @param string $order ordinal * @param string $value value * @return bool */public function Zadd ($key, $order, $va Lue) {return $this->redis->zadd ($key, $order, $value);} /** * to $value member's order value, increase $num, can be negative * @param string $key * @param string $num ordinal * @param string $value value * @return return new or Der */public function Zincry ($key, $num, $value) {return $this->redis->zincry ($key, $num, $value);} /** * Delete element with value = @param string $key * @param stirng $value * @return bool */public function Zrem ($key, $value) {return $ This->redis->zrem ($key, $value);} /** * Set in order increments, 0 represents the first element, 1 represents the last element * @param string $key * @param int $start * @param int $end * @return Array|bool */ Public Function Zrange ($key, $start, $end) {return $this->redis->zrange ($key, $start, $end);} /** * Set in order descending order, 0 represents the first element, 1 represents the last element * @param string $key * @param int $start * @param int $end * @return Array|bool */ Public Function Zrevrange ($key, $start, $end) {return $this->redis->zrevrange ($key, $start, $end);} The/** * Collection returns an element between the specified order after the order is incremented.     * min and Max can be-inf and +inf for maximum value, minimum * @param string $key * @param int $start * @param int $end * @package array $option parameter * Withscores=>true, which indicates that the array is labeled as the order value, returns the indexed array by default * Limit=>array (0,1), which starts with 0 and takes a record. * @return Array|bool */public function Zrangebyscore ($key, $start = '-inf ', $end = "+inf", $option =array ()) {return $this- >redis->zrangebyscore ($key, $start, $end, $option);} The/** * Collection returns the element between the specified order after descending order in order.     * min and Max can be-inf and +inf for maximum value, minimum * @param string $key * @param int $start * @param int $end * @package array $option parameter * Withscores=>true, which indicates that the array is labeled as the order value, returns the indexed array by default * Limit=>array (0,1), which starts with 0 and takes a record. * @return Array|bool */public function Zrevrangebyscore ($key, $start = '-inf ', $end = "+inf", $option =array ()) {return $ This->redis->zrevrangebyscore ($key, $start, $end, $option);} /** * Returns the number of order values between start end * @param unknown $key * @param unknown $start * @param unknown $end */public function Zcount ($key, $start, $end) {return $thisRedis->zcount ($key, $start, $end);} /** * Returns the order value of value * @param unknown $key * @param unknown $value */public function Zscore ($key, $value) {return $this-&G T;redis->zscore ($key, $value);} /** * Returns the set to score the sorted number of the specified member, starting with 0. * @param unknown $key * @param unknown $value */public function Zrank ($key, $value) {return $this->redis->zrank ($key, $value);} /** * Returns the set to score the sorted number of the specified member, starting with 0. * @param unknown $key * @param unknown $value */public function Zrevrank ($key, $value) {return $this->redis->zrevrank ($key, $value);} /** * Delete the elements in the collection, the score value between the start end includes the start end * min and Max can be-inf and +inf represents the maximum value, the minimum value * @param unknown $key * @param unknown $star T * @param unknown $end * @return The number of deleted members. */public function Zremrangebyscore ($key, $start, $end) {return $this->redis->zremrangebyscore ($key, $start, $end );} /** * Returns the number of collection elements. * @param unknown $key */public function Zcard ($key) {return $this->redis->zcard ($key);} /********************* Queue Operations Command ************************//** * Inserts an element at the end of the queue * @paraM unknown $key * @param unknown $value * Returns the queue Length */public function Rpush ($key, $value) {return $this->redis->rpush ( $key, $value);} /** * Insert an element at the tail of the queue if key does not exist, do nothing * @param unknown $key * @param unknown $value * Return Queue Length */public function rpushx ($key, $val UE) {return $this->redis->rpushx ($key, $value);} /** * Insert an element in the head of the queue * @param unknown $key * @param unknown $value * Returns the queue Length */public function Lpush ($key, $value) {return $this ->redis->lpush ($key, $value);} /** * Insert an element in the queue header if key does not exist, do nothing * @param unknown $key * @param unknown $value * Return Queue Length */public function lpushx ($key, $valu e) {return $this->redis->lpushx ($key, $value);} /** * Returns the queue Length * @param unknown $key */public function Llen ($key) {return $this->redis->llen ($key);} /** * Returns the element of the queue specified interval * @param unknown $key * @param unknown $start * @param unknown $end */public function Lrange ($key, $start , $end) {return $this->redis->lrange ($key, $start, $end);} /** * Returns the element of the specified index in the queue * @param unknown $key * @param unknown $index */publIC function LIndex ($key, $index) {return $this->redis->lindex ($key, $index);} /** * Sets the value of the specified index in the queue. * @param unknown $key * @param unknown $index * @param unknown $value */public function LSet ($key, $index, $value) {return $t His->redis->lset ($key, $index, $value);} /** * Delete count elements with value Vaule * Php-redis Extended Data order is not the same as the order of the command, do not know if it is not a bug * count>0 start from the tail * >0 start from the head * = 0 Delete all * @param unkn Own $key * @param unknown $count * @param unknown $value */public function Lrem ($key, $count, $value) {return $this->redis ->lrem ($key, $value, $count);} /** * Deletes and returns the header element in the queue. * @param unknown $key */public function Lpop ($key) {return $this->redis->lpop ($key);} /** * Delete and return the tail element in the queue * @param unknown $key */public function Rpop ($key) {return $this->redis->rpop ($key);} /*************redis string Operation Command *****************//** * Set a key * @param unknown $key * @param unknown $value */public function Set ($key, $value) {return $this->redis->set ($key, $value);} /** * Get a key * @param unknown $key */public functionGet ($key) {return $this->redis->get ($key);} /** * Set an expiry time key * @param unknown $key * @param unknown $expire * @param unknown $value */public function Setex ($key, $e Xpire, $value) {return $this->redis->setex ($key, $expire, $value);} /** * Set a key, if key exists, do nothing. * @param unknown $key * @param unknown $value */public function setnx ($key, $value) {return $this->redis->setnx ($key, $value);} /** * Bulk Set key * @param unknown $arr */public function Mset ($arr) {return $this->redis->mset ($arr);} /*************redis unordered Collection Operations Command *****************//** * Returns all elements in the collection * @param unknown $key */public function smembers ($key) { return $this->redis->smembers ($key);} /** * Find the difference set of 2 sets * @param unknown $key 1 * @param unknown $key 2 */public function Sdiff ($key 1, $key 2) {return $this->redis-& Gt;sdiff ($key 1, $key 2);} /** * Add collection. The extension does not support bulk additions due to version issues.        The package is made here * @param unknown $key * @param string|array $value */public function Sadd ($key, $value) {if (!is_array ($value))    $arr =array ($value);      Else   $arr = $value; foreach ($arr as $row) $this->redis->sadd ($key, $row);} /** * Returns the number of elements in an unordered collection * @param unknown $key */public function SCard ($key) {return $this->redis->scard ($key);} /** * Remove an element from the collection * @param unknown $key * @param unknown $value */public function Srem ($key, $value) {return $this->redis- >srem ($key, $value);} /*************redis Management Operations Command *****************//** * Select database * @param int $dbId Database ID number * @return bool */public function Select ($ DbId) {$this->dbid= $dbId; return $this->redis->select ($dbId);} /** * Empties the current database * @return bool */public function flushdb () {return $this->redis->flushdb ();} /** * Returns the current library status * @return array */public function info () {return $this->redis->info ();} /** * Synchronously saves data to disk */public function save () {return $this->redis->save ();} /** * Asynchronously saves data to disk */public function BgSave () {return $this->redis->bgsave ();} /** * Returns the last time saved to disk */public function Lastsave () {return $this->redis->lastsave ();} /** * Return key, support * Multiple characters,? a character * only * denotes all * @pAram String $key * @return array */public function keys ($key) {return $this->redis->keys ($key);} /** * Delete the specified key * @param unknown $key */public function del ($key) {return $this->redis->del ($key);} /** * Determine if a key value is present * @param unknown $key */public function exists ($key) {return $this->redis->exists ($key);} /** * Sets the expiration time unit for a key to the seconds * @param unknown $key * @param unknown $expire */public function expire ($key, $expire) {return $this ->redis->expire ($key, $expire);} /** * Returns how long a key has expired, unit seconds * @param unknown $key */public function ttl ($key) {return $this->redis->ttl ($key);} /** * Set When a key expires, time is a timestamp * @param unknown $key * @param unknown $time */public function exprieat ($key, $time) {return $this->redis->expireat ($key, $time);} /** * Close Server link */public function close () {return $this->redis->close ();} /** * Close all connections */public static function CloseAll () {foreach (static::$_instance as $o) {if ($o instanceof self) $ O->close ();}} /** The connection is not closed here because session writes are destroyed after all objects have been deleted.Public Function __destruct () {return $this->redis->close ();} **//** * Returns the current database key number */public function Dbsize () {return $this->redis->dbsize ();}    /** * Returns a random key */public function Randomkey () {return $this->redis->randomkey ();} /** * Gets the current database ID * @return int */public function getdbid () {return $this->dbid;} /** * Returns the current password */public function GetAuth () {return $this->auth;} Public Function GetHost () {return $this->host;} Public Function Getport () {return $this->port;} Public Function Getconninfo () {return array (' host ' = = $this->host, ' port ' = = $this->port, ' auth ' = $thi S->auth);} /********************* transaction-related methods ************************//** * Monitor key, which is one or more keys to add an optimistic lock * during this time if the value of key changes, Cannot set value for key * Can regain value of key. * @param unknown $key */public function Watch ($key) {return $this->redis->watch ($key);} /** * Cancel the current link to all Key's Watch * EXEC command or DISCARD command is executed first, then do not need to execute unwatch */public function unwatch () {return $this->re Dis->unwatch ();} /* * Open a transaction * The invocation of a transaction has two modes Redis::multi and Redis::P ipeline, * default is Redis::multi mode, * Redis::P ipeline pipe mode faster, But there is no guarantee that atomicity may result in loss of data */public function multi ($type =\redis::multi) {return $this->redis->multi ($type);} /** * Executes a transaction * after receiving the EXEC command into the transaction execution, the execution of any command in the transaction fails, the remaining commands are still executed */public function EXEC () {return $this->redis->exec ();} /** * Rollback a transaction */public function discard () {return $this->redis->discard ();} /** * Test the current link is not already invalidated * No expiration returned +pong * Invalid return false */public function ping () {return $this->redis->ping ();} Public Function auth ($auth) {return $this->redis->auth ($auth);} /********************* custom methods for simplifying operations ************************//** * Get a set of ID numbers * @param unknown $prefix * @param unknown $ IDS */public function Hashall ($prefix, $ids) {if ($ids ==false) return false;if (is_string ($ids)) $ids =explode (', ', $ids) , $arr =array (), foreach ($ids as $id) {$key = $prefix. '. $id, $res = $this->hgetall ($key), if ($res!=false) $arr []= $res;} return $arr;} /** * Generates a message that is placed in the Redis database. Use library number No. 0. * @param String|array $msg */public function Pushmessage ($lkey, $msg) {if (Is_array ($msg)) $msg =json_encode ($msg);        $key =md5 ($msg); If the message already exists, delete the old message, the current message is quasi//echo $n = $this->lrem ($lkey, 0, $key). "    \ n ";    Reset New Message $this->lpush ($lkey, $key);    $this->setex ($key, 3600, $msg); return $key;} /** * Get a batch Delete key command * @param unknown $keys * @param unknown $dbId */public function Delkeys ($keys, $dbId) {$redisInfo = $t    His->getconninfo ();        $CMDARR =array (' redis-cli ', '-a ', $redisInfo [' auth '], '-h ', $redisInfo [' Host '],    '-P ', $redisInfo [' Port '], '-N ', $dbId,);    $redisStr =implode (' ', $CMDARR); $cmd = "{$redisStr} KEYS \" {$keys}\ "|    xargs {$redisStr} del "; return $cmd;}}

PHP Redis Database Operation class

Related Article

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.