Php Redis function usage example summary [with a php connection to redis Singleton class], redisphp
This example summarizes the usage of php Redis functions. We will share this with you for your reference. The details are as follows:
I have been using Redis with PHP all the time, but I always feel insecure. I just want to use this time to get it in one breath,
I tried all the Redis commands in PHP almost all over again, including the correct values returned. Even if I forgot the next time, I can check them directly ~ You can also rest assured to use it.
Test environment: PHP: 5.5 Redis: 2.4.6
Reference: https://github.com/phpredis/phpredis
Tips:
For string, set, sort set, and hash addition and modification operations, it is the same command, but when it is modified, the return value is still 0 if it is successful in time.
For the list structure, there is a free method for adding, deleting, and modifying differences.
<? Php/* 1. connection */$ redis = new Redis (); $ redis-> connect ('2017. 0.0.1 ', 62.16,1); // transient link, local host, port 6379, abandon link for more than 1 second $ redis-> open ('123456. 0.0.1 ', 62.16,1); // short link (same as above) $ redis-> pconnect ('100. 127. 0.0.1 ', 6 rows, 1); // persistent link, local host, port 6379, abandon link for more than 1 second $ redis-> popen ('100. 127. 0.0.1 ', 62.16,1); // long link (same as above) $ redis-> auth ('Password'); // login verification password, return [true | false] $ redis-> select (0); // select the redis database, 0 ~ 15. A total of 16 databases $ redis-> close (); // release resources $ redis-> ping (); // check whether the database is connected again, [+ pong] $ redis-> ttl ('key'); // view the expiration time [-1 | timestamps] $ redis-> persist ('key '); // remove the expiration time [1 | 0] $ redis-> sort ('key', [$ array]); // return or save the sorted elements in the given list, set, and sorted set key. $ array is the parameter limit! [Very powerful with $ array] [array | false]/* 2. common Operation Categories */$ redis-> expire ('key', 10); // set the expiration time [true | false] $ redis-> move ('key ', 15); // move the key in the current database to the 15 database [0 | 1] // string $ redis-> strlen ('key '); // get the length of the current key $ redis-> append ('key', 'string '); // append a string to an existing key value [number of appends] $ redis-> incr ('key'); // auto-increment 1. If the key does not exist, value 1 (only valid for integers, 64-bit in decimal format, str in redis) [new_num | false] $ redis-> incrby ('key', $ num ); // auto increment $ num. If the value does not exist, the value must be an integer [new_num | false] $ redis. -> Decr ('key'); // auto-minus 1, [new_num | false] $ redis-> decrby ('key', $ num ); // auto-Subtract $ num, [new_num | false] $ redis-> setex ('key', 10, 'value'); // key = value, valid for 10 seconds [true] // list $ redis-> llen ('key'); // returns the length of the list key. If no key exists, 0 is returned, [len | 0] // set $ redis-> scard ('key'); // returns the base number of the set key (the number of elements in the set ). [Num | 0] $ redis-> sMove ('key1', 'key2', 'member '); // move the member element from the key1 set to the key2 set. [1 | 0] // Zset $ redis-> zcard ('key'); // returns the base number of the set key (number of elements in the set ). [Num | 0] $ redis-> zcount ('key', 0,-1); // returns the sorted set key, members whose score values are between min and max (the default value is min or max. [Num | 0] // hash $ redis-> hexists ('key', 'field '); // check whether the hash contains a field, [1 | 0] $ redis-> hincrby ('key', 'field', $ int_num ); // Add (+ |-) num, [new_num | false] $ redis-> hlen ('key') to the field value in the key of the hash table '); // return the number of fields in the hash table key. [Num | 0]/* 3. server */$ redis-> dbSize (); // returns the number of keys in the current database $ redis-> flushAll (); // clear the entire redis [total true] $ redis-> flushDB (); // clear the current redis database [total true] $ redis-> save (); // synchronization ?? Store data to a disk-dump. rdb [true] $ redis-> bgsave (); // asynchronous ?? Store Data to disk-dump. rdb [true] $ redis-> info (); // query the status of the current redis [verson: 2.4.5 ......] $ redis-> lastSave (); // time when the key was last stored [timestamp] $ redis-> watch ('key', 'keyn '); // monitor one or more keys. If the key is changed by other commands before the transaction is executed, then the transaction will be interrupted [true] $ redis-> unwatch ('key', 'keyn'); // cancel monitoring one or more) key [true] $ redis-> multi (Redis: MULTI); // when you start a transaction, multiple commands in the transaction block are put into a queue in sequence, finally, the EXEC command is executed within an atomic time. $ Redis-> multi (Redis: PIPELINE); // enable the PIPELINE. Multiple commands in the transaction block are put into a queue in sequence, finally, the EXEC command is executed within an atomic time. $ Redis-> exec (); // execute the commands in all transaction blocks. [return values of all commands in the transaction block are arranged in order of command execution, when an operation is interrupted, null value false is returned.]/* 4. string, key-value pair, the same operation as creating an update */$ redis-> setOption (Redis: OPT_PREFIX, 'hf _'); // set the table prefix to hf _ $ redis-> set ('key', 1 ); // set key = aa value = 1 [true] $ redis-> mset ($ arr ); // set one or more key values [true] $ redis-> setnx ('key', 'value'); // key = value, if the key exists, false [| true] $ redis-> get ('key') is returned. // obtain the key [value] $ redis-> mget ($ arr ); // (string | arr), returns the value of the queried key $ redis-> del ($ key_arr); // (String | arr) delete key, supporting batch deletion of arrays [number of returned deletions] $ redis-> delete ($ key_str, $ key2, $ key3 ); // Delete keys, [del_num] $ redis-> getset ('old _ key', 'new _ value'); // obtain the key value and then assign a value again, [old_value | false]/* 5. list stack structure. Pay attention to the end of the table header and create separate update operations */$ redis-> lpush ('key', 'value'); // Add, only one value can be inserted into the table header of the list key. If no value exists, the [list length | false] $ redis-> rpush ('key', 'value') is created '); // Add. Only one value can be inserted to the end of the table of the list key. [length of the list | false] $ redis-> lInsert ('key', Redis: AFTER, 'value', 'new _ Value '); // Add, insert the value to the list key, before or after the value. [New_len | false] $ redis-> lpushx ('key', 'value'); // Add, only one value can be inserted into the header of the list key, [list length not created | false] $ redis-> rpushx ('key', 'value'); // Add, only one value can be inserted at the end of the table with the list key. [list length | false] $ redis-> lpop ('key') is not created; // Delete, remove and return the Header element of the list key, [Deleted element | false] $ redis-> rpop ('key'); // Delete, remove, and return the end element of the list key, [Deleted element | false] $ redis-> lrem ('key', 'value', 0); // Delete, based on the value of the parameter count, remove the element count = (0 |-n header to the end | + n table to the end to remove n values) that are equal to the parameter value in the list) [Number of removed items | 0] $ redis-> Ltrim ('key', start, end); // Delete, list trim, retain (start, end) value Range: [true | false] $ redis-> lset ('key', index, 'new _ V'); // you can specify the number of headers, returns the value of the element whose index is the subscript of the list key to new_v, [true | false] $ redis-> lindex ('key', index); // query, returns the index element [value | false] $ redis-> lrange ('key', 0,-1) in the key list, stop | 0,-1) return the elements in the specified range in the list key. The range is specified by the offset start and stop. [Array | false]/* 6.Set, no duplicate member. Create an update operation */$ redis-> sadd ('key', 'value1 ', 'value2 ', 'valuen'); // Add, modify, and add one or more member elements to the set key. The member elements that already exist in the set are ignored. [Insert_num] $ redis-> srem ('key', 'value1 ', 'value2', 'valuen'); // Delete, remove one or more member elements from the set key. nonexistent member elements are ignored. [del_num | false] $ redis-> smembers ('key'); // query, returns all the members of the set key [array | ''] $ redis-> sismember ('key', 'member '); // determine whether the member element is a member of the set key [1 | 0] $ redis-> spop ('key'); // Delete, remove and return a random element in the set [member | false] $ redis-> srandmember ('key'); // query, returns a random element in the set [member | false] $ redis-> sinter ('key1', 'key2', 'keyn'); // query Returns the intersection of all given sets [array | false] $ redis-> sunion ('key1', 'key2', 'keyn'); // query, returns the union of all given sets [array | false] $ redis-> sdiff ('key1', 'key2', 'keyn'); // query, returns the difference set of all given sets [array | false]/* 7. zset, no duplicate member, sorting order, same operation for creating updates */$ redis-> zAdd ('key', $ score1, $ member1, $ scoreN, $ memberN ); // Add, modify, and add one or more member elements and their score values to the sorted set key. [Num | 0] $ redis-> zrem ('key', 'member1', 'membern'); // Delete and remove one or more members from the sorted set key, nonexistent members are ignored. [Del_num | 0] $ redis-> zscore ('key', 'member'); // query, using the value anti-authorization [num | null] $ redis-> zrange ('key', $ start, $ stop); // query, pass (score from small to large) [sorting ranking range] takes the member value and returns the [array | null] $ redis-> zrevrange ('key', $ start, $ stop); // query, get the member value through (score from big to small) [ranking range], and return the key of the sorted set, [array | null] $ redis-> zrangebyscore ('key', $ min, $ max [, $ config]); // query, get the member value through the scroe weight range, and return the [array | null] $ redis-> Zrevrangebyscore ('key', $ max, $ min [, $ config]); // query, get the member value through the scroe weight range, and return to the sorted set key, [array | null] $ redis-> zrank ('key', 'member ') member in the specified range (from large to small); // query, [member ranking] [order | null] $ redis-> zrevrank ('key', 'member') in the ranking result of member value query (score from small to large '); // query. [member ranking] [order | null] $ redis-> ZINTERSTORE () in the ranking result of the score (from large to small (); // intersection $ redis-> ZUNIONSTORE (); // difference set/* 8. hash, table structure, create and update the same operation */$ redis-> hset ('key', 'field ', 'value ');/ /Add, modify, set the field value in the key of the hash table to value. If no value is created, overwrite [1 | 0] $ redis-> hget ('key ', 'field'); // query, value: [value | false] $ arr = array ('one' => 1, 2, 3); $ arr2 = array ('one ', 0, 1); $ redis-> hmset ('key', $ arr); // Add, modify, and set multi-value $ arr to an array (index | Association, $ arr [key] = field, [true] $ redis-> hmet ('key', $ arr2); // query to obtain the specified field, [$ arr | false] $ redis-> hgetall ('key'); // query and return all fields and values in the hash table key. [If the key does not exist, an empty table is returned] $ redis-> hkeys ('key'); // query. All fields in the hash table key are returned. [If the key does not exist, an empty table is returned] $ redis-> hvals ('key'); // query. All values in the hash table key are returned. [If the key does not exist, an empty table is returned] $ redis-> hdel ('key', $ arr2); // Delete to delete the specified field, the Nonexistent domain is ignored. [num | false]?>
Appendix: single-instance php connection to the redis Database
<? Phpclass RedisConnect {/*** Redis ip ** @ var string */const REDISHOSTNAME = "127.0.0.1 "; /*** Redis port *** @ var int */const REDISPORT = 6379;/*** Redis timeout time ** @ var int */const REDISTIMEOUT = 0; /*** Redis password ** @ var unknown_type */const REDISPASSWORD = "ehualu";/*** Redis DBname ** @ var int */const REDISDBNAME = 12; /*** class Singleton ** @ var object */private static $ instance ;/** * Redis connection handle ** @ var object */private $ redis;/*** private constructor, prevent out-of-class instantiation ** @ param unknown_type $ dbnumber */private function _ construct () {// link database $ this-> redis = new Redis (); $ this-> redis-> connect (self: REDISHOSTNAME, self: REDISPORT, self: REDISTIMEOUT); $ this-> redis-> auth (self: REDISPASSWORD ); $ this-> redis-> select (self: REDISDBNAME);}/*** private clone function to prevent external clone objects */private function _ clone (){} /*** The only public static method of the class. Obtain the unique entry of the class singleton. ** @ return object */public static function getRedisInstance () {if (! (Self: $ instance instanceof self) {self: $ instance = new self ();} return self: $ instance ;} /*** get the connection instance of redis ** @ return Redis */public function getRedisConn () {return $ this-> redis ;} /*** clean up when switching a single instance */public function _ destruct () {self: $ instance-> redis-> close (); self:: $ instance = NULL; }}?>