Summary of common skills of PHP operation Redis

  • 2021-09-24 21:40:24
  • OfStack

In this paper, the common skills of PHP operating Redis are described with examples. Share it for your reference, as follows:

1. Redis Connection and Authentication


// Connection parameters: ip Port, Connection Timeout, Connection Successful Return true Otherwise, return false
$ret = $redis->connect('127.0.0.1', 6379, 30);
// Password Authentication: Successful Return true Otherwise, return false
$ret = $redis->auth('123456');

2. String operation


//设置键值:成功返回true,否则返回false
$redis->set('mystr', 'Welcome!');
//获取键值:成功返回String类型键值,若key不存在或不是String类型则返回false
$ret = $redis->get('mystr');
//从某个key所存储的字符串的指定偏移量开始,替换为另1指定字符串,成功返回替换后新字符串的长度。
$ret = $redis->setRange('mystr', 7, ' to Beijing!');
//获取存储在指定key中字符串的子字符串。
$ret = $redis->getRange('mystr', 0, 6);
//设置新值,返回旧值:若key不存在则设置值,返回false
$ret = $redis->getSet('mystr', 'hi man');
//1次设置多个键值对:成功返回true。
$ret = $redis->mset(['name' => 'jet', 'age' => 18]);
//1次获取多个key的值:返回1个键值对数组,其中不存在的key值为false。
$ret = $redis->mget(['name', 'age']);
//设置指定key的值及其过期时间,单位:秒。
//参数:键名,过期时间,键值。成功返回true。
$ret = $redis->setex('name', 10, 'jetwu');
//以毫秒为单位设置指定key的值和过期时间。成功返回true。
$ret = $redis->psetex('name', 10, 'jetwu');
//key的值不存在时,才为其设置值。key不存在且设置成功返回true,否则返回false。
$ret = $redis->setnx('name', 'boby');
//setnx命令的批量操作。只有在给定所有key都不存在的时候才能设置成功,只要其中1个key存在,所有key都无法设置成功。
$ret = $redis->msetnx(['country' => 'China', 'city' => 'Shenzhen']);
//获取指定key存储的字符串的长度,key不存在返回0,不为字符串返回false。
$ret = $redis->strlen('name');
//将指定key存储的数字值增加1。若key不存在会先初始化为0再增加1,若key存储的不是整数值则返回false。成功返回key新值。
$ret = $redis->incr('age');
//给指定key存储的数字值增加指定增量值。
$ret = $redis->incrBy('age', 10);
//给指定key存储的数字值增加指定浮点数增量。
$ret = $redis->incrByFloat('age', 1.5);
//将指定key存储的数字值减1。
$ret = $redis->decr('age');
//将指定key存储的数字值减去指定减量值。
$ret = $redis->decrBy('age', 10);
//为指定key追加值到原值末尾,若key不存在则相对于set()函数。
$ret = $redis->append('mystr', 'haha');

3. Hash operation


// For hash Assign values to fields in the table. Successful return 1 Failure returns 0 . If hash If the table does not exist, the table will be created before assigning values. If the field already exists, the old values will be overwritten. 
$ret = $redis->hSet('user', 'realname', 'jetwu');
// Get hash Gets or sets the value of the specified field in the. If hash Table does not exist false . 
$ret = $redis->hGet('user', 'realname');
// View hash Whether a field of the table exists, the existence returns true Otherwise, return false . 
$ret = $redis->hExists('user', 'realname');
// Delete hash Tabular 1 Fields, deleting multiple fields is not supported. Successful return 1 Otherwise, return 0 . 
$ret = $redis->hDel('user', 'realname');
// At the same time, set a hash Multiple field values of the table. Successful return true . 
$ret = $redis->hMset('user', ['name' => 'jet', 'age' => 18]);
// At the same time get a hash Multiple field values of the table. Where the field value that does not exist is false . 
$ret = $redis->hMget('user', ['name', 'age']);
// Gets a hash All the fields and values of the table. 
$ret = $redis->hGetAll('user');
// Gets a hash The names of all fields in the table. hash Returns an empty array when the table does not exist, key Not for hash Table is returned when false . 
$ret = $redis->hKeys('user');
// Gets a hash The values of all fields in the table. 
$ret = $redis->hVals('user');
// For hash A field assignment that does not exist in the table. If hash If the table does not exist, it will be created first, and if the field already exists, nothing will be done. Setting successfully returns true Otherwise, return false . 
$ret = $redis->hSetNx('user', 'realname', 'jetwu');
// Gets a hash The number of fields in the table. If hash Table does not exist return 0 If key Not for hash Table returns false . 
$ret = $redis->hLen('user');
// For hash The specified field in the table is added with the specified increment value, and if the increment value is negative, it is equivalent to subtraction operation. If hash If the table does not exist, create it first, and if the field does not exist, initialize the value to 0 Then, if the field value is a string, it will return false . Set the new value of the returned field successfully. 
$ret = $redis->hIncrBy('user', 'age', 10);
// For hash The specified field in the table plus the specified floating-point number increment value. 
$ret = $redis->hIncrBy('user', 'age', 1.5);

4. List operation


//从list头部插入1个值。
$ret = $redis->lPush('city', 'guangzhou');
//从list尾部插入1个值。
$ret = $redis->rPush('city', 'guangzhou');
//获取列表指定区间中的元素。0表示列表第1个元素,-1表示最后1个元素,-2表示倒数第2个元素。
$ret = $redis->lrange('city', 0, -1);//查看队列所有元素
//将1个插入已存在的列表头部,列表不存在时操作无效。
$ret = $redis->lPushx('city', 'hangzhou');
//将1个或多个值插入已存在的列表尾部,列表不存在时操作无效。
$ret = $redis->rPushx('city', 'hangzhou');
//移除并返回列表的第1个元素,若key不存在或不是列表则返回false。
$ret = $redis->lPop('city');
//移除并返回列表的最后1个元素,若key不存在或不是列表则返回false。
$ret = $redis->rPop('city');
//移除并获取列表的第1个元素。如果列表没有元素则会阻塞列表直到等待超时或发现可弹出元素为止。
//参数:key,超时时间(单位:秒)
//返回值:[0=>key,1=>value],超时返回[]
$ret = $redis->blPop('city', 10);
//移除并获取列表的最后1个元素。如果列表没有元素则会阻塞列表直到等待超时或发现可弹出元素为止。
//参数:key,超时时间(单位:秒)
//返回值:[0=>key,1=>value],超时返回[]
$ret = $redis->brPop('city', 10);
//移除列表中最后1个元素,将其插入另1个列表头部,并返回这个元素。若源列表没有元素则返回false。
$ret = $redis->rpoplpush('city', 'city2');
//移除列表中最后1个元素,将其插入另1个列表头部,并返回这个元素。如果列表没有元素则会阻塞列表直到等待超时或发现可弹出元素为止。
//参数:源列表,目标列表,超时时间(单位:秒)
//超时返回false
$ret = $redis->brpoplpush('city', 'city2', 10);
//返回列表长度。
$ret = $redis->lLen('city');
//通过索引获取列表中的元素。若索引超出列表范围则返回false。
$ret = $redis->lindex('city', 0);
//通过索引设置列表中元素的值。若是索引超出范围,或对1个空列表进行lset操作,则返回false。
$ret = $redis->lSet('city', 2, 'changsha');
//在列表中指定元素前或后面插入元素。若指定元素不在列表中,或列表不存在时,不执行任何操作。
//参数:列表key,Redis::AFTER或Redis::BEFORE,基准元素,插入元素
//返回值:插入成功返回插入后列表元素个数,若基准元素不存在返回-1,若key不存在返回0,若key不是列表返回false。
$ret = $redis->lInsert('city', Redis::AFTER, 'changsha', 'nanjing');
//根据第3个参数count的值,移除列表中与参数value相等的元素。
//count > 0 : 从表头开始向表尾搜索,移除与value相等的元素,数量为count。
//count < 0 : 从表尾开始向表头搜索,移除与value相等的元素,数量为count的绝对值。
//count = 0 : 移除表中所有与value相等的值。
//返回实际删除元素个数
$ret = $redis->lrem('city', 'guangzhou', -2);
//对1个列表进行修剪,只保留指定区间的元素,其他元素都删除。成功返回true。
$ret = $redis->ltrim('city', 1, 4);

5. Set operation


// Will 1 Elements are added to the collection, and elements that already exist in the collection are ignored. If the collection does not exist, it is created first, if key Is not a collection type false Returns if the element already exists 0 Successful insertion returns 1 . 
$ret = $redis->sAdd('myset', 'hello');
// Returns all members of the collection. 
$ret = $redis->sMembers('myset');
// Determines whether the specified element is a member of the specified collection true Otherwise, return false . 
$ret = $redis->sismember('myset', 'hello');
// Returns the number of elements in the collection. 
$ret = $redis->scard('myset');
// Removes and returns the 1 Random elements. 
$ret = $redis->sPop('myset');
// Returns the 1 One or more random member elements, the number and condition of the elements returned by the first of the function 2 Parameters count Decides: 
// If count Is a positive number and is less than the collection cardinality, the command returns 1 Contains count An array of 10 elements, with different elements in the array. 
// If count Is greater than or equal to the collection cardinality, the entire collection is returned. 
// If count Is a negative number, the command returns 1 The elements in the array may be repeated many times, and the length of the array is count Gets or sets the absolute value of. 
$ret = $redis->sRandMember('myset', 2);
// Removes the specified in the collection 1 Elements, ignoring elements that do not exist. Delete successfully returned 1 Otherwise, return 0 . 
$ret = $redis->srem('myset', 'hello');
// Iterates the elements in the collection. 
// Parameters: key Iterator variable, match pattern, number of elements returned at a time (default is 10 A) 
$ret = $redis->sscan('myset', $it, 'a*', 5);
// Returns the specified member from the 1 Source collections are moved to 1 A collection of destinations. If the source collection does not exist or does not contain the specified element, nothing is done and returns false . 
// Parameters: Source collection, destination collection, moving element 
$ret = $redis->sMove('myset', 'myset2', 'aaa');
// Returns the difference set between all given sets, and the nonexistent set is regarded as an empty set. 
$ret = $redis->sDiff('myset', 'myset2', 'myset3');
// Stores the difference set between all given sets in the specified destination set. Overwrite the destination collection if it already exists. Returns the number of elements in the difference set. 
// Parameter: Parameter 1 Parameters are the target set, and the difference set is stored. 
$ret = $redis->sDiffStore('myset3', 'myset', 'myset2');
// Returns the intersection of all given collections, and nonexistent collections are considered empty. 
$ret = $redis->sInter('myset', 'myset2', 'myset3');
// Stores the intersection of all given collections in the specified destination collection. Overwrite the destination collection if it already exists. Returns the number of intersecting elements. 
// Parameter: Parameter 1 Parameters are the target set, and the intersection is stored. 
$ret = $redis->sInterStore('myset4', 'myset', 'myset2', 'myset3');
// Returns the union of all given collections, and nonexistent collections are treated as empty sets. 
$ret = $redis->sUnion('myset', 'myset2', 'myset3');
// Stores the union of all given collections in the specified destination collection. Overwrite the destination collection if it already exists. Returns the number of union elements. 
// Parameter: Parameter 1 Parameters are the target set, and the union set is stored. 
$ret = $redis->sUnionStore('myset4', 'myset', 'myset2', 'myset3');

6. Zset operation


// Will 1 One or more member elements and their fractions are added to the ordered set. If a member is already a member of an ordered set, the score value of the member is updated and the member element is reinserted to ensure that the member is in the correct position. The fractional value can be an integer value or a double-precision floating-point number. 
$ret = $redis->zAdd('scores', 98, 'English', 90, 'physics');
// Returns the members of a specified interval in an ordered set. Members are sorted incrementally by fraction value, and those with the same fraction value are sorted in lexicographic order. 
// Parameter: Parameter 4 Parameters indicate whether to return the score value of each element, and the default is false . 
$ret = $redis->zRange('scores', 0, -1, true);// View Zset All members and their respective fractions 
// Returns the members of a specified interval in an ordered set. Members are sorted in descending order by fraction value, and those with the same fraction value are sorted in reverse order of lexicon order. 
$ret = $redis->zReverseRange('scores', 0, -1, true);
// Returns a list of members of a specified fraction interval in an ordered set, sorted incrementally by fraction value, and sorted lexically for those with the same fraction value. Closed intervals are used by default. 
$ret = $redis->zRangeByScore('scores', 90, 100, ['withscores'=>true]);
// Returns a list of members of the specified fraction interval in an ordered set, sorted in descending order by fraction value, and sorted in reverse order by dictionary order for those with the same fraction value. Note that when the interval is represented, the large value comes first and the small value comes last, and the closed interval is used by default. 
$ret = $redis->zRevRangeByScore('scores', 100, 90, ['withscores'=>true]);
// Iterates the elements in an ordered collection. 
// Return value: [ Element name => Fractional value ,,..]
$ret = $redis->zscan('scores', $it, '', 10);
// Returns the number of elements of the specified ordered set. 
$ret = $redis->zCard('scores');
// Returns the number of members of a specified score interval in an ordered set. 
$ret = $redis->zCount('scores', 90, 100);
// Returns the score value of the specified member in an ordered set. Returns if the member does not exist false . 
$ret = $redis->zScore('scores', 'math');
// Returns the ranking of specified members in an ordered set, sorted incrementally by points. The lowest score is ranked as 0 . 
$ret = $redis->zRank('scores', 'chemistry');
// Returns the ranking of specified members in an ordered set, sorted in descending order. The ranking of the person with the largest score value is 0 . 
$ret = $redis->zRevRank('scores', 'chemistry');
// To remove the 1 One or more members, ignoring nonexistent members. Returns the number of deleted elements. 
$ret = $redis->zRem('scores', 'chemistry', 'English');
// Removes all members of the specified ranking interval in the ordered set. 
$ret = $redis->zRemRangeByRank('scores', 0, 2);
// Removes all members of the specified fractional value interval in the ordered set. 
$ret = $redis->zRemRangeByScore('scores', 80, 90);
// Increments the score value of the specified member in the ordered set by the specified increment value. If it is negative, do subtraction; If the ordered set does not exist, create it first; If there is no corresponding member in the ordered set, add it first, and then operate it finally. 
$ret = $redis->zIncrBy('scores', 2, 'Chinese');
// Calculate a given 1 The intersection of ordered sets or sets, and stores it in the 1 Orderly concentration of objectives. The score value of a member in the result set is the sum of the score values of that member in all given sets. 
$ret = $redis->zinterstore('zset3', 'zset2', 'zset1');
// Calculate a given 1 A union of or more ordered sets and stores them in the 1 Orderly concentration of objectives. The score value of a member in the result set is the sum of the score values of that member in all given sets. 
$ret = $redis->zunionstore('zset3', 'zset2', 'zset1');

For more readers interested in PHP related content, please check the topics on this site: "Summary of php+redis Database Programming Skills", "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: