Рубрики
Uncategorized

Общий синтаксис redis в PHP [рекомендация]

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

Redis-это тип службы структуры C/S, C относится к клиенту, S относится к серверу, клиент и сервер могут взаимодействовать через сеть. Для redis службы redis должны быть установлены на стороне сервера. А как насчет клиентской стороны? На самом деле redis предоставляет API-интерфейсы для многих языков. Он может взаимодействовать между клиентом и сервером с помощью языка. Для языка PHP мы можем взаимодействовать между клиентом и сервером, установив расширение redis.

Операция строкового типа

Строка-это самый основной тип redis, а строковый тип-двоичная безопасность. Это означает, что строки redis могут содержать любые данные. Например, изображения в формате jpg или сериализованные объекты

$redis->set('key','TK');
$redis->set('number','1');
$redis - > setex ('key', 5,'TK'); and // Set the key value valid for 5 seconds
$redis - > psetex ('key', 5000,'TK'); and // set the key value to be valid for 5000 milliseconds (the same as 5 seconds)
$redis - > setnx ('key','XK'); // If the key value exists, return false does not exist, return true
$redis - > delete ('key'); deleting key values can pass in array ('key1','key2') and delete multiple keys
$redis - > getSet ('key','XK'); // Set the value of the key to XK and return the original value of the key TK
 $ret = $redis - > multi () // batch transaction processing, not guaranteeing the atomicity of processing data
  ->set('key1', 'val1')
  ->get('key1')
  ->setnx('key', 'val2')
  ->get('key2')
  ->exec();
$redis - > watch ('key'); // Monitor key is modified by other clients
       If KEY is modified between calling watch () and exec (), exec fails.
$redis->publish('chan-1', 'hello, world!'); // send message. 
$redis - > exists ('key'); // verify the existence of the key and return true
$redis - > incr ('number'); // key plus 1
$redis - > incrby ('number', - 10); // keys plus or minus 10
$redis - > incrByFloat ('number', +/- 1.5); // keys plus decreases
$redis - > decr ('number'); // keys minus 1
$redis - > decrBy ('number', 10); // keys minus 10
$mget = $redis - > mget (array ('number','key'); // batch fetch key value, return an array
$redis - > Mset (array ('key0'=>'value0','key1'=>'value1'); //batch setting of key values
$redis->msetnx(array('key0' => 'value0', 'key1' => 'value1')); 
          // batch key setting, similar to batch operation of setnx () method
$redis - > append ('key','-Smudge'); and // the original key value TK, appending the value to the key value, with the key value TK-Smudge
$redis - > getRange ('key', 0, 5); // Key value interception starts at position 0 and ends at position 5
$redis - > getRange ('key', - 6, - 1); // String interception starts at - 6 (penultimate position 6) and ends at - 1 (penultimate position 1)
$redis->setRange('key', 0, 'Smudge'); 
         // Replace strings in key values, 0 means starting at 0
          How many characters are replaced and how many positions are replaced, in which Chinese characters occupy two positions?
$redis - > strlen ('key'); and // key length
$redis->getBit('key');
$redis->setBit('key');

Операция со списком списков

$redis - > delete ('list-key'); //delete linked list
$redis - > lPush ('list-key','A'); // Insert the list head / left, return the list length
$redis - > rPush ('list-key','B'); // Insert the tail / right side of the list, return the length of the list
$redis->lPushx('list-key', 'C'); 
     // Insert the head/left side of the list, the list does not return 0, if it exists, the insertion is successful and the current length of the list is returned.
$redis->rPushx('list-key', 'C'); 
     // Insert at the end/right of the list, the list does not return 0, if it exists, the insert is successful and the current length of the list is returned.
$redis - > lPop ('list-key'); // Return to VALUE at the top (left) of LIST, then in, first out (stack)
$redis - > rPop ('list-key'); // Return to VALUE at the tail (right) of LIST, FIFO (queue)
$redis->blPop();
$redis->brPop();
$redis->lSize('list-key'); 
     // If it is a linked list, it returns the length of the linked list, and an empty list returns 0. 
      If it is not a linked list or is not empty, return false and judge non-linked list "=== false"       
$redis - > lGet ('list-key', -1); // Get the list element 0 from the index to get the left one-1 to get the last one
$redis - > lSet ('list-key', 0,'X'); //0 position element replaced by X
$redis->lRange('list-key', 0, 3); 
     // Link list interception ends at position 3 starting from 0 and ends at position - 1 to get all of the starting positions.
$redis - > lTrim ('list-key', 0, 1); //intercept linked list (irreversible) starts with index 0 and ends with index 1 
$redis - > lRem ('list-key','C', 2); //list deletes 2 C elements from left
$redis->lInsert('list-key', Redis::BEFORE, 'C', 'X'); 
     // Insert X, Redis:: AfTER before the C element. 
      If the list does not exist, insertion fails to return 0. If the element does not exist, return - 1.
$redis->rpoplpush('list-key', 'list-key2'); 
     // Pop up an element from the end of the source LIST
      And press this element from the top (left) of the target LIST into the target LIST. 
$redis->brpoplpush();
     // The blocking version of rpoplpush, which has a third parameter to set the blocking time
      That is, if the source LIST is empty, then the time to listen for timeout can be blocked, and if there are elements, the operation can be performed.

Установить тип коллекции

Set disordered sets do not allow duplicate element servers to implement multiple set operations
$redis - > sMembers ('key'); // Get all the elements in the container key
$redis->sAdd('key' , 'TK');
     // (Insert from the left, the last element inserted is at 0), and if TK already exists in the collection, return false 
      There is no successful addition to return true
$redis - > sRem ('key','TK'); //Remove TK from container
$redis - > sMove ('key','key1','TK'); // Move the element TK in the easy key to container key1 and return TRUE successfully
$redis - > sIsMember ('key','TK'); // Check whether VALUE is a member of the SET container?
$redis - > sCard ('key'); // Number of members returning to SET container
$redis - > sPop ('key'); // Randomly return an element in the container and remove it
$redis - > sRandMember ('key'); // Random return to an element in the container without removing it
$redis->sInter('key','key1'); 
  // Returning the intersection of two sets does not intersect returns an empty array. If there is only one set of parameters, the complete array corresponding to the set is returned.
$redis - > sInterStore ('store','key','key1'); // Save the intersection of collection key and collection key1 into container store and successfully return 1
$redis - > sUnion ('key','key1'); and // set key and set key1 union attention, even if multiple sets have the same element and only one is retained

$redis->sUnionStore('store','key','key1'); 
   // The union of the set key and the set key1 is stored in the set store. Note that even if multiple sets have the same element, only one is retained.
$redis - > sDiff ('key','key1','key2'); and // returns an array element that exists in the key set but not in the set key1 key2

Установите тип данных

Магазины, как и set, представляют собой набор строк, за исключением того, что каждый элемент связан со счетом двойного типа. Тип списка redis на самом деле является двунаправленным списком, в котором каждый дочерний элемент имеет строковый тип. * *

$redis->zAdd('tkey', 1, 'A'); 
       // Inserted into the set tkey, the A element associates a score, and the insertion returns 1 successfully.
        At the same time, the collection element cannot be repeated, if the element already exists, return 0.
$redis - > zRange ('tkey', 0, - 1); // Gets collection elements from 0 to - 1
$redis->zRange('tkey',0,-1, true); 
     // Gets the set elements, from 0 to - 1, and returns an associative array with scores 
      Array ([A]=> 0.01, [B]= > 0.02, [D]=> 0.03) where decimal is derived from the second parameter of the zAdd method
$redis - > zDelete ('tkey','B'); //Remove element B from set tkey successfully returns 1, fails to return 0
$redis - > zRevRange ('tkey', 0, - 1); // Gets collection elements from 0 to - 1, and the array is processed in descending order according to score

$redis->zRevRange('tkey', 0, -1,true); 
    // Gets the collection elements, from 0 to - 1, and returns the score associative array in descending order
$redis->zRangeByScore('tkey', 0, 0.2,array('withscores' => true)); 
   // Get the score element in the interval [0,0.2] of several tkeys, and the score is sorted from low to high.
    Elements with the same score are arranged in dictionary order, and withscores controls the return of associative arrays
$redis->zRangeByScore('tkey', 0.1, 0.36, array('withscores' => TRUE, 'limit' => array(0, 1)));
    // where 0 and 1 in limit represent starting from 0 in the eligible set and scanning backwards to return an associative array
$redis - > zCount ('tkey', 2, 10); // Gets the number of score elements in tkey in the interval [2, 10]
$redis - > zRemRangeByScore ('tkey', 1, 3); // Remove the element of score in tkey in the interval [1, 3] (with boundary)
$redis->zRemRangeByRank('tkey', 0, 1); 
       // The Default element score is incremental, removing elements in tkey from 0 to - 1
$redis - > zSize ('tkey'); // Returns the number of elements stored in the ordered set corresponding to the key
$redis - > zScore ('tkey','A'); and // Returns the score value of element A in the set tkey
$redis->zRank('tkey', 'A'); 
      // Returns the index value of element A in the set tkey 
       The elements in the Z set are arranged from low to high by score, i.e. the lowest score index is 0.
$redis - > zIncrBy ('tkey', 2.5,'A'); // Add the score value of element A in set tkey to 2.5
$redis->zUnion('union', array('tkey', 'tkey1')); 
  // Merge the set tkey and set tkey1 elements into the set union, and the elements in the new set cannot be repeated
   Returns the number of elements in the new set. If element A exists in both tkey and tkey1, then the score addition of the merged element A
$redis->zUnion('ko2', array('k1', 'k2'), array(5, 2)); 
  // The set K1 and set K2 are combined in k02, the number of elements in array (5,1) corresponds to the subset, and then 5 corresponds to k1. 
   Each element score of K1 is multiplied by 5, the same as 1 corresponds to k2, and each element score of K2 is multiplied by 1. 
   The elements are then sorted incrementally, with the same element score (SUM) added by default.
$redis->zUnion('ko2', array('k1', 'k2'), array(10, 2),'MAX'); 
  // After multiplying each subset by a factor, the elements are sorted incrementally, and the score of the same element is the maximum (MAX).
   MIN can also be set to a minimum
$redis->zInter('ko1', array('k1', 'k2')); 
  // Set K1 and set K2 intersect at K01 and are sorted incrementally according to score value
   If the set elements are the same, the score values of the elements in the new set are added.
$redis->zInter('ko1', array('k1', 'k2'), array(5, 1)); 
  // set K1 and set K2 are intersected in k01, the number of elements in array (5,1) corresponds to the subset, and then 5 corresponds to k1. 
   Each element score of K1 is multiplied by 5, the same as 1 corresponds to k2, and each element score of K2 is multiplied by 1. 
   Then the element score is sorted incrementally, with the same element score (SUM) added by default
$redis->zInter('ko1', array('k1', 'k2'), array(5, 1),'MAX'); 
  // After multiplying each subset by a factor, the element score is sorted incrementally, and the same element score takes the maximum value (MAX).
   MIN can also be set to a minimum

Тип хэш-данных

Хэш Redis – это таблица сопоставления поля и значения строкового типа. Его операции добавления и удаления составляют O (1) (среднее значение). хэш особенно подходит для хранения объектов.

$redis - > hSet ('h','name','TK'); // Add the name field value to the H table as TK
$redis->hSetNx('h', 'name', 'TK');
   // Add the name field value to the H table as TK. If the value of the field name exists, return false or return true.
$redis - > hGet ('h','name'); and // Get the value of the name field in the H table
$redis - > hLen ('h'); // Gets the length of the H table, that is, the number of fields
$redis - > hDel ('h','email'); //Delete the email field in the H table
$redis - > hKeys ('h'); // Gets all the fields in the H table
$redis - > hVals ('h'); // Gets all field values in the H table
$redis - > hGetAll ('h'); // Gets all fields and values in the H table and returns an associative array (fields are key values)
$redis - > hExists ('h','email'); // Determine whether the email field exists and the table h does not exist and return false
$redis->hSet('h', 'age', 28);
$redis->hIncrBy('h', 'age', -2); 
 // Set the age field value plus (-2) in the H table to return false if value is a non-numeric value, otherwise return value after operation
$redis->hIncrByFloat('h', 'age', -0.33); 
  // Set the age field value plus (-2.6) in the H table to return false if value is a non-numeric value otherwise
   Return value after operation (15 decimal points reserved)
$redis - > hMset ('h', array ('score'=> 80','salary'=> 2000); //table h batch setting fields and values
$redis - > hMGet ('h', array ('score','salary'); // Table h gets the value of the field in batches

резюме

Выше приведена общая грамматика redis в PHP, представленная Xiaobian. Я надеюсь, что это будет вам полезно. Если у вас есть какие-либо вопросы, пожалуйста, оставьте мне сообщение, и Xiaobian ответит вам вовремя. Большое вам спасибо за вашу поддержку в развитии peer.

Оригинал: “https://developpaper.com/the-common-syntax-of-redis-in-php-recommendation/”