Рубрики
Uncategorized

Операция PHP база данных redis общий пример метода краткое описание

Автор оригинала: David Wong.

В этой статье описываются общие методы работы PHP с базой данных redis. Подробности заключаются в следующем:

1. Установите расширение PHP_ Redis для работы с redis

http://pecl. php .net/пакет/redis

Выберите расширение, соответствующее версии PHP вашей системы.

2, Подключение и проверка Redis

connect('127.0.0.1', 6379, 60);
//Password verification
$redis->auth('');

3, Строковая операция redis

//Set the value of the key, and return true on success and false on failure
$ret = $redis->set('app_id', '1234567890');
var_dump($ret);
//Get the value of the key, return the key value successfully, return false if it fails
$ret = $redis->get('app_id');
var_dump($ret);
//Set the value of the key from the specified offset, replace it with the specified string, and successfully return the length of the new string
$ret = $redis->setRange('app_id', 2, '666');
var_dump($ret);
//Get the value of the key, through the start index and end index, the obtained sub string includes the start index and end index
$ret = $redis->getRange('app_id', 0, -1);
var_dump($ret);
$ret = $redis->getRange('app_id', 3, 6);
var_dump($ret);
//Set the new value and return the old value. If the key does not exist, set the value and return false
$ret = $redis->getSet('app_id', '666666666');
var_dump($ret);
//Setting multiple key value pairs at once
$ret = $redis->mset(['db_name' => 'test', 'db_host' => 'localhost']);
var_dump($ret);
//Get multiple key value pairs at a time and return an array
$ret = $redis->mget(['db_name', 'db_host']);
var_dump($ret);
//Set key value and expiration time, unit: seconds, return true successfully
$ret = $redis->setex('name', 10, 'hello');
var_dump($ret);
//Set the key value, and the expiration time is in milliseconds
$ret = $redis->psetex('age', 10, '28');
var_dump($ret);
//If the key does not exist, the value will be set. If the key does not exist and the setting is successful, true will be returned. Otherwise, false will be returned
$ret = $redis->setnx('name', 'test');
var_dump($ret);
//The batch operation of setnx can only be set successfully when all the keys do not exist. Otherwise, if one key exists, all the keys cannot be set successfully
$RET = $redis - > msetnx (['name '= >'Hello','age '= >'28','sex '= >'male'];
var_dump($ret);
//Get the string length of the key value. If the key does not exist, return 0. If the value is not a string, return false
$ret = $redis->strlen('name');
var_dump($ret);
//Add 1 to the number value stored in the key. If the key does not exist, it will be initially 0 and then 1. If the number value stored is not a number value, it will return false and the new value-added value will be returned successfully
$ret = $redis->incr('age');
var_dump($ret);
//Add the number value stored in the key to the specified increment value
$ret = $redis->incrBy('age', 10);
var_dump($ret);
//Add the numeric value stored in the key to the specified floating-point increment value
$ret = $redis->incrByFloat('age', 0.25);
var_dump($ret);
//Subtract 1 from the digital value stored in the key
$ret = $redis->decr('age');
var_dump($ret);
//Decrement the number value stored in the key by the specified decrement value
$ret = $redis->decrBy('age', 10);
var_dump($ret);
//Add the value of the specified key to the end of the original value. If the key does not exist, it is equivalent to the set() function
$ret = $redis->append('name', 'hahaha');
var_dump($ret);

4, Хэш-операция redis

//Set the key value in hash table, return 1 if success, return 0 if failure
$ret = $redis->hSet('user', 'name', 'xiaoxu');
var_dump($ret);
//Gets the value of the key in the hash table, and returns false if it does not exist in the hash table
$ret = $redis->hget('user', 'name');
var_dump($ret);
//Judge whether the field in hash table exists, return true if it exists, and return false if it fails
$ret = $redis->hExists('user', 'name');
var_dump($ret);
//Delete the fields in hash table, return 1 if success, return 0 if failure
$ret = $redis->hDel('user', 'name');
var_dump($ret);
//Batch setting the values of fields in hash table, returning true successfully
$RET = $redis - > hmset ('user ', ['name' = >'xiaoxu ','age' = > 28, 'sex' = >'male '];
var_dump($ret);
//Get the values of fields in hash table in batch
$ret = $redis->hMGet('user', ['name', 'age', 'sex']);
var_dump($ret);
//Get all the fields and values in the hash table
$ret = $redis->hGetAll('user');
var_dump($ret);
//Get all the field names in the hash table, and return an empty array when hash does not exist
$ret = $redis->hKeys('user');
var_dump($ret);
//Get all the field values in the hash table
$ret = $redis->hVals('user');
var_dump($ret);
//Set the value when the field in the hash table does not exist. If the hash table does not exist, create it first. If the field exists, do not do any operation.
//If the setting is successful, return true, otherwise return false
$ret = $redis->hSetNx('user', 'height', 172);
var_dump($ret);
//Get the number of fields in hash table, hash does not exist, return 0
$ret = $redis->hlen('user');
var_dump($ret);
//Adds the specified increment value to the field value in the hash table. If the increment value is negative, it is equivalent to subtraction
//If the hash table does not exist, it will be created first. If the field does not exist, it will initially be 0. If the field value is a string, it will return false
$ret = $redis->hIncrBy('user', 'age', 10);
var_dump($ret);
//Adds the specified floating-point increment value to the field value in the hash table
$ret = $redis->hIncrByFloat('user', 'age', 0.25);
var_dump($ret);

5, Перечислите операции redis

//Inserts a value from the head of the list
$ret = $redis->lpush('students', 'xiaoxu');
$ret = $redis->lpush('students', 'xiaoxu2');
var_dump($ret);
//Inserts a value from the end of the list
$ret = $redis->rpush('students', 'xiaowang');
$ret = $redis->rpush('students', 'xiaowang2');
var_dump($ret);
//Gets the elements in the specified range of the list, 0 for the first element and - 1 for the last element
$ret = $redis->lRange('students', 0, -1);
var_dump($ret);
//Insert a value into the head of an existing list. The operation is invalid when the list does not exist.
$ret = $redis->lPushx('students', 'xiaozhang');
var_dump($ret);
//Insert a value at the end of an existing list. The operation is invalid when the list does not exist.
$ret = $redis->rPushx('students', 'xiaoli');
var_dump($ret);
//Move out and get the first element of the list, and return false if the key does not exist or is not a list.
$ret = $redis->lpop('students');
var_dump($ret);
//Move out and get the last element of the list, and return false if the key does not exist or is not a list.
$ret = $redis->rpop('students');
var_dump($ret);
//Move out and get the first element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or the pop-up element is found.
//Timeout unit: seconds
$ret = $redis->blPop('students', 10);
var_dump($ret);
//Move out and get the last element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or the pop-up element is found.
$ret = $redis->brPop('students', 10);
var_dump($ret);
//Remove the last element from the list, insert it into the head of another list, and return the element. Returns false if the source list has no elements.
$ret = $redis->rpoplpush('students', 'students2');
var_dump($ret);
//Remove the last element from the list, insert it into the head of another list, and return the element.
//If the list has no elements, it blocks the list until the wait times out or a pop-up element is found.
//Timeout unit: seconds
$ret = $redis->brpoplpush('students', 'students2', 10);
var_dump($ret);
//Gets the length of the list
$ret = $redis->lLen('students2');
var_dump($ret);
//Get the elements in the list by index. If the index exceeds the list range, false is returned.
$ret = $redis->lIndex('students2', 0);
var_dump($ret);
//Sets the value of the element in the list by index. If the index is out of range or an empty list is lset, false is returned.
$ret = $redis->lSet('students2', 0, 'xiaomi');
var_dump($ret);
//Inserts an element before or after the specified element in the list. If the specified element is not in the list or the list does not exist, no operation is performed.
//Parameters: key of list, redis:: after or redis:: before, benchmark element, insert element
//Return value: the number of elements in the list after successful insertion is returned. If the benchmark element does not exist, - 1 is returned. If the key does not exist, 0 is returned. If the key is not in the list, false is returned.
$ret = $redis->lInsert('students2', Redis::AFTER, 'xiaomi', 'xiaoji');
var_dump($ret);
//According to the value of the third parameter count, remove the elements in the list that are equal to the parameter value.
//Count > 0: search from the header to the end of the table to remove the elements equal to value. The number is count.
//Count < 0: search the header from the end of the table, remove the elements equal to value, and the number is the absolute value of count.
//Count = 0: removes all values equal to value in the table.
//Returns the actual number of deleted elements
$ret = $redis->lrem('students2', 'xiaomi', 0);
var_dump($ret);
//Prune the list to keep only the elements in the specified range, and delete all other elements. True returned on success.
$ret = $redis->ltrim('students2', 0, -1);
var_dump($ret);

6, Установите режим работы redis

//Add one or more members to the collection
//If the collection does not exist, it will be created first. If the key is not a collection type, it will return false
//If the element already exists, 0 is returned and 1 is returned after insertion.
$ret = $redis->sAdd('friend', 'xiaoxu', 'xiaowang', 'xiaoli', 'xiaozhang');
var_dump($ret);
//Returns all members of the collection.
$ret = $redis->sMembers('friend');
var_dump($ret);
//Determine whether the element is a member of the set key
$ret = $redis->sIsMember('friend', 'xiaoxu');
var_dump($ret);
//Returns the number of members in the collection.
$ret = $redis->scard('friend');
var_dump($ret);
//Removes and returns a random element in the collection
$ret = $redis->spop('friend');
var_dump($ret);
//Returns one or more random member elements in the set. The number and condition of the returned elements are determined by the second parameter count of the function
//If count is a positive number and less than the cardinality of the collection, the command returns an array containing count elements with different elements.
//If count is greater than or equal to the cardinality of the collection, the entire collection is returned.
//If count is negative, then the command returns an array. The elements in the array may repeat many times, and the length of the array is the absolute value of count.
$ret = $redis->sRandMember('friend', 2);
var_dump($ret);
//Removes an element specified in the collection, ignoring elements that do not exist. If the deletion is successful, 1 will be returned, otherwise 0 will be returned.
$ret = $redis->sRem('friend', 'xiaowang');
var_dump($ret);
//Iterate the elements in the set
//Parameters: set key, iterator variable, matching pattern, number of elements returned each time (default is 10)
$ret = $redis->sScan('friend', $iter, 'xiao*', 5);
var_dump($ret);
var_dump($iter);
//Moves a specified member from a source collection to a destination collection.
//If the source collection does not exist or does not contain the specified element, no operation is performed and false is returned.
//Parameters: source set, target set, move element
$ret = $redis->sMove('friend', 'friend2', 'xiaoxu');
var_dump($ret);
//Returns the difference set between all given sets. Nonexistent sets are considered empty sets.
$ret = $redis->sDiff('friend', 'friend2');
var_dump($ret);
//Stores the difference sets between all given sets in the specified destination set.
//If the destination set already exists, it is overridden. Returns the number of difference elements.
//Parameter: the first parameter is the target set, which stores the difference set.
$ret = $redis->sDiffStore('friend3', 'friend2', 'friend');
var_dump($ret);
//Returns the intersection of all given sets. Nonexistent sets are treated as empty sets.
$ret = $redis->sInter('friend', 'friend2');
var_dump($ret);
//Stores the intersection of all given sets in the specified destination set.
//If the destination set already exists, it is overridden. Returns the number of intersection elements.
//Parameter: the first parameter is the target set, which stores the intersection.
$ret = $redis->sInterStore('friend4', 'friend2', 'friend');
var_dump($ret);
//Returns the union of all given sets. Nonexistent sets are treated as empty sets.
$ret = $redis->sUnion('friend', 'friend2');
var_dump($ret);
//Stores the union of all given sets in the specified destination set.
//If the destination set already exists, it is overridden. Returns the number of union elements.
//Parameter: the first parameter is the target set, which stores the union set.
$ret = $redis->sUnionStore('friend5', 'friend2', 'friend');
var_dump($ret);

7、 Работа отсортированного набора в redis

//Adds one or more member elements and their fractional values to an ordered set.
//If a member is already a member of an ordered set, the fractional value of the member is updated, and the member element is re inserted 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', 60, 'math', 80, 'english', 75, 'chinese');
var_dump($ret);
//Returns the members in the specified interval of an ordered set. Members are sorted according to the score from small to large, and those with the same score value are sorted according to dictionary order.
//Parameter: the fourth parameter indicates whether to return the fractional value of each element, which is false by default.
$ret = $redis->zRange('scores', 0, -1, true);
var_dump($ret);
//Returns the members in the specified interval of an ordered set. Members are sorted according to the score value from large to small, and those with the same score value are sorted according to the reverse order of dictionary order.
$ret = $redis->zRevRange('scores', 0, -1, true);
var_dump($ret);
//Returns the member list of the specified score range in the ordered set, sorted by the score value from small to large,
//Those with the same score value are sorted in dictionary order. Closed intervals are used by default.
$ret = $redis->zRangeByScore('scores', 60, 90, ['withscores' => true]);
var_dump($ret);
//Returns the member list of the specified score range in the ordered set, sorted by the descending score value,
//If the score value is the same, it will be sorted according to the reverse order of dictionary order.
//Note that when the interval is expressed, the large value comes first and the small value comes later. By default, the closed interval is used.
$ret = $redis->zRevRangeByScore('scores', 90, 60, ['withscores' => true]);
var_dump($ret);
//Iterates over elements in an ordered set.
//Return value: [element name = > fractional value,...]
$ret = $redis->zScan('scores', $iter, '*', 10);
var_dump($ret);
var_dump($iter);
//Returns the number of elements in the specified ordered set.
$ret = $redis->zCard('scores');
var_dump($ret);
//Returns the number of members of a specified fraction interval in an ordered set.
$ret = $redis->zCount('scores', 60, 90);
var_dump($ret);
//Returns the fractional value of a specified member in an ordered set. Returns false if the member does not exist.
$ret = $redis->zScore('scores', 'english');
var_dump($ret);
//Returns the ranking of specified members in an ordered set, sorted from small to large. The lowest score is 0.
$ret = $redis->zRank('scores', 'english');
var_dump($ret);
//Returns the ranking of the specified members in the ordered set, sorted by the score value from large to small. The highest score is 0.
$ret = $redis->zRevRank('scores', 'english');
var_dump($ret);
//Remove one or more members from the ordered set, ignoring nonexistent members. Returns the number of deleted elements.
$ret = $redis->zRem('scores', 'english');
var_dump($ret);
//Removes all members of the specified ranking range from the ordered set.
$ret = $redis->zRemRangeByRank('scores', 0, 2);
var_dump($ret);
//Removes all members of the specified score range from the ordered set.
$ret = $redis->zRemRangeByScore('scores', 60, 90);
var_dump($ret);
//Adds the specified increment value to the fractional value of the specified member in the ordered set.
//If the number is negative, subtraction will be done. If the ordered set does not exist, it will be created first. If there is no corresponding member in the ordered set, it will be added first, and then operated finally.
$ret = $redis->zIncrBy('scores', 2, 'chinese');
var_dump($ret);
//The intersection of one or more ordered sets is calculated and stored in a destination ordered set.
//Parameters: target ordered set, multiple ordered sets, weight of multiple ordered sets, and method of merging ordered sets (the value of the score of the member multiplied by the weight is added or compared)
$redis->zAdd('s1', 1, '111');
$redis->zAdd('s1', 2, '222');
$redis->zAdd('s1', 3, '333');
$redis->zAdd('s2', 4, '222');
$redis->zAdd('s2', 5, '333');
$ret = $redis->zInter('s3', ['s1', 's2'], [1, 5], 'SUM');
// ['222' => 22, '333' => 28]
var_dump($ret);
$ret = $redis->zInter('s4', ['s1', 's2'], [1, 5], 'MIN');
// ['222' => 2, '333' => 3]
var_dump($ret);
$ret = $redis->zInter('s5', ['s1', 's2'], [1, 5], 'MAX');
// ['222' => 20, '333' => 25]
var_dump($ret);
//Computes the union of one or more ordered sets and stores them in a destination ordered set.
//The fractional value of a member in the result set is the sum of the fractional values of that member in all given sets.
$ret = $redis->zUnion('s6', ['s1', 's2'], [5, 1], 'SUM');
// ['111' => 5, '222' => 14, '333' => 20]
var_dump($ret);
$ret = $redis->zUnion('s7', ['s1', 's2'], [5, 1], 'MIN');
// ['222' => 4, '111' => 5, '333' => 5]
var_dump($ret);
$ret = $redis->zUnion('s8', ['s1', 's2'], [5, 1], 'MAX');
// ['111' => 5, '222' => 10, '333' => 15]
var_dump($ret);

Для получения дополнительной информации о PHP читатели, интересующиеся этим сайтом, могут ознакомиться со следующими темами: краткое изложение навыков программирования баз данных PHP + redis, вводный курс объектно-ориентированного программирования PHP, вводный курс базовой грамматики PHP, навыки работы с массивами PHP, краткое описание использования строк PHP “Руководство по работе с базами данных PHP + MySQL” и “Общие навыки работы с базами данных PHP”

Я надеюсь, что эта статья будет полезна для программирования на PHP.