Home > Backend Development > PHP Tutorial > A complete collection of predis operations for php to connect to redis

A complete collection of predis operations for php to connect to redis

WBOY
Release: 2016-07-25 08:46:27
Original
1349 people have browsed it

predis is an operation library for PHP to connect to redis. Since it is completely written in PHP and uses a lot of namespaces and closures, it only supports PHP5.3 or above. Therefore, the measured performance is average, 25,000 reads and writes per second. I believe it will be changed to c The performance of PHP written in the language will be greatly improved after being extended (for example, using C to extend phpredis https://github.com/owlient/phpredis).

It is also very simple to store session data in redis:
session.save_handler = redis
session.save_path = “tcp://127.0.0.1:6379″

The following is a summary of some operations and will be continuously updated.

  1. //Use autoload to load related libraries. The focus here is to require $file;
  2. spl_autoload_register(function($class) {
  3. $file = __DIR__.'/lib/Predis/'.$class.'.php ';
  4. if (file_exists($file)) {
  5. require $file;
  6. return true;
  7. }
  8. });
  9. //Configure the connection IP, port, and corresponding database
  10. $server = array(
  11. 'host' => '127.0.0.1',
  12. 'port' => 6379,
  13. 'database' = > 15
  14. );
  15. $redis = new Client($server);
  16. //Normal set/get operation
  17. $redis->set('library', 'predis');
  18. $retval = $redis- >get('library');
  19. echo $retval; //Show 'predis'
  20. //setex set a storage time limit
  21. $redis->setex('str', 10, 'bar'); // Indicates that the storage validity period is 10 seconds
  22. //setnx/msetnx is equivalent to the add operation and will not overwrite the existing value
  23. $redis->setnx('foo',12); //true
  24. $redis->setnx( 'foo',34); //false
  25. //getset operation, a variant of set, the result returns the value before replacement
  26. $redis->getset('foo',56);//returns 34
  27. // incrby/incr/decrby/decr Increment and decrement the value
  28. $redis->incr('foo'); //foo is 57
  29. $redis->incrby('foo',2); //foo is 59
  30. //exists detects whether a certain value exists
  31. $redis->exists('foo');//true
  32. //del deletes
  33. $redis->del('foo');//true
  34. //type type detection, string returns string, list returns list, set table returns set/zset, hash table returns hash
  35. $redis->type('foo');//does not exist, returns none
  36. $redis ->set('str','test');
  37. $redis->type('str'); //String, return string
  38. //Append connect to the existing string
  39. $redis-> ;append('str','_123'); //Return the accumulated string length 8, this time str is 'test_123'
  40. //setrange partial replacement operation
  41. $redis->setrange('str', 0,'abc'); //Return 3, when parameter 2 is 0, it is equivalent to the set operation
  42. $redis->setrange('str',2,'cd');//Return 4, which means starting from the second Replace after the character, then 'str' is 'abcd'
  43. //substr part of the acquisition operation
  44. $redis->substr('str',0,2);//means starting from the 0th, get to the 0th 2 characters, 3 in total, return 'abc'
  45. //strlen Get the string length
  46. $redis->strlen('str'); //Return 4
  47. //setbit/getbit bit storage and acquisition
  48. $redis->setbit('binary',31,1); //Indicates that 1 is stored in the 31st bit. There may be a big or small endian problem here? But it doesn't matter, there should be no problem with getbit.
  49. $redis-> ;getbit('binary',31); //return 1
  50. //keys fuzzy search function, supports * sign and ? sign (match one character)
  51. $redis->set('foo1',123);
  52. $redis->set('foo2',456);
  53. $redis->keys('foo*'); //Return the array of foo1 and foo2
  54. $redis->keys('f?o?' ); //Same as above
  55. //randomkey randomly returns a key
  56. $redis->randomkey(); //It may return 'foo1' or 'foo2' or any other key that exists in redis
  57. //rename /renamenx Rename the key. The difference is that renamenx does not allow changing to an existing key
  58. $redis->rename('str','str2'); //Change the key originally named 'str' to 'str2'
  59. //expire sets the timeliness of key-value, ttl gets the remaining validity period, persist is reset to permanent storage
  60. $redis->expire('foo', 1); //Set the validity period to 1 second
  61. $redis->ttl('foo'); //Return the validity period value 1s
  62. $redis->expire('foo'); //Cancel the expire behavior
  63. //dbsize Returns the total number of records in the current redis database
  64. $redis->dbsize();
  65. /*
  66. Queue operation
  67. */
  68. //rpush/rpushx Ordered list operation, insert elements from the queue
  69. //lpush/lpushx The difference between rpush/rpushx is insertion Go to the head of the queue, same as above, 'x' means to only operate on existing keys
  70. $redis->rpush('fooList', 'bar1'); //Return a list of length 1
  71. $redis- >lpush('fooList', 'bar0'); //Returns the length of a list 2
  72. $redis->rpushx('fooList', 'bar2'); //Returns 3, rpushx only works on existing queues Add, otherwise return 0
  73. //llen returns the current list length
  74. $redis->llen('fooList');//3
  75. //lrange returns the elements of a range in the queue
  76. $redis->lrange( 'fooList',0,1); //The returned array contains a total of 2 elements from the 0th to the 1st
  77. $redis->lrange('fooList',0,-1); //Return the 0th to The last one is equivalent to returning all elements. Note that negative numbers are often used in redis, the same below
  78. //lindex returns the list elements at the specified sequence position
  79. $redis->lindex('fooList',1); //Return 'bar1'
  80. //lset Modify the value at the specified position in the queue
  81. $redis->lset('fooList',1,'123');//Modify the element at position 1 and return true
  82. / /lrem Delete the specified number of characters from the left in the queue
  83. $redis->lrem('fooList',1,'_'); //Delete 1 character '_' from the left (use -1 from the right) in the queue (if any)
  84. //lpop/rpop pops (and deletes) the leftmost or rightmost element similar to a stack structure
  85. $redis->lpop('fooList'); //'bar0'
  86. $redis- >rpop('fooList'); //'bar2'
  87. //ltrim Queue modification, keep a few elements from the left, delete the rest
  88. $redis->ltrim('fooList', 0,1); //Keep The 0th to 1st elements from the left
  89. //rpoplpush pops elements from one queue and pushes them to another queue
  90. $redis->rpush('list1','ab0');
  91. $redis-> ;rpush('list1','ab1');
  92. $redis->rpush('list2','ab2');
  93. $redis->rpush('list2','ab3');
  94. $redis->rpoplpush('list1','list2');//Result list1 =>array('ab0'),list2 =>array('ab1','ab2','ab3')
  95. $ redis->rpoplpush('list2','list2');//Also applies to the same queue, move the last element to the head list2 =>array('ab3','ab1','ab2')
  96. //linsert inserts elements before or after the specified element in the middle of the queue
  97. $redis->linsert('list2', 'before','ab1','123'); //Indicates before element 'ab1' Insert '123'
  98. $redis->linsert('list2', 'after','ab1','456'); //Indicates inserting '456' after element 'ab1'
  99. //blpop/brpop blocking And wait until a queue is not empty, then pop out the leftmost or rightmost element (this function can be said to be very useful outside of PHP)
  100. //brpoplpush also blocks and waits for the operation, and the result is the same as rpoplpush
  101. $redis ->blpop('list3',10); //If list3 is empty, wait until the first element is popped when it is not empty. Timeout after 10 seconds
  102. /**
  103. set table operation
  104. */
  105. / /sadd adds elements, returns true, returns false repeatedly
  106. $redis->sadd('set1','ab');
  107. $redis->sadd('set1','cd');
  108. $redis-> ;sadd('set1','ef');
  109. //srem Remove the specified element
  110. $redis->srem('set1','cd'); //Delete the 'cd' element
  111. //spop Pop the first element
  112. $redis->spop('set1');
  113. //smove Move the specified element of the current set table to another set table
  114. $redis->sadd('set2','123');
  115. $redis->smove('set1','set2','ab');//Move 'ab' in 'set1' to 'set2', return true or false
  116. //scard returns the current set table Number of elements
  117. $redis->scard('set2');//2
  118. //sismember Determine whether the element belongs to the current table
  119. $redis->sismember('set2','123'); //true or false
  120. //smembers returns all elements of the current table
  121. $redis->smembers('set2'); //array('123','ab');
  122. //sinter/sunion/sdiff returns two The intersection/union/complement of the elements in the table
  123. $redis->sadd('set1','ab');
  124. $redis->sinter('set2','set1'); //return array ('ab')
  125. //sinterstore/sunionstore/sdiffstore Copy the intersection/union/complement elements of the two tables to the third table
  126. $redis->set('foo',0);
  127. $ redis->sinterstore('foo','set1'); //This is equivalent to copying the contents of 'set1' to 'foo' and converting 'foo' to a set table
  128. $redis->sinterstore ('foo',array('set1','set2')); //Copy the same elements in 'set1' and 'set2' to the 'foo' table, overwriting the original content of 'foo'
  129. // srandmember returns a random element in the table
  130. $redis->srandmember('set1');
  131. /**
  132. Ordered set table operation
  133. */
  134. //sadd adds an element and sets the serial number, returns true, and returns false repeatedly
  135. $ redis->zadd('zset1',1,'ab');
  136. $redis->zadd('zset1',2,'cd');
  137. $redis->zadd('zset1',3, 'ef');
  138. //zincrby increases or decreases the index value of the specified element and changes the order of the elements
  139. $redis->zincrby('zset1',10,'ab');//returns 11
  140. // zrem removes the specified element
  141. $redis->zrem('zset1','ef'); //true or false
  142. //zrange returns the elements in the specified range in the table in position order
  143. $redis->zrange( 'zset1',0,1); //Return the elements between positions 0 and 1 (two)
  144. $redis->zrange('zset1',0,-1); //Return the position 0 and the last one Elements between one element (equivalent to all elements)
  145. //zrevrange Same as above, returns the elements in the specified range in the table, in reverse order
  146. $redis->zrevrange('zset1',0,-1); //The order of elements is opposite to zrange
  147. //zrangebyscore/zrevrangebyscore returns the elements of the specified index range in the table in order/descending order
  148. $redis->zadd('zset1',3,'ef');
  149. $redis-> ;zadd('zset1',5,'gh');
  150. $redis->zrangebyscore('zset1',2,9); //Return elements array('ef',' between index values ​​2-9 gh')
  151. //Parameter form
  152. $redis->zrangebyscore('zset1',2,9,'withscores'); //Return elements between index values ​​2-9 and contain index values ​​array(array(' ef',3),array('gh',5))
  153. $redis->zrangebyscore('zset1',2,9,array('withscores' =>true,'limit'=>array(1 , 2))); //Return elements between index values ​​2-9, 'withscores' =>true means including the index value; 'limit'=>array(1, 2), means return at most 2 items, The result is array(array('ef',3),array('gh',5))
  154. //zunionstore/zinterstore Store the union/intersection of multiple tables into another table
  155. $redis-> zunionstore('zset3',array('zset1','zset2','zset0')); //Save the union of 'zset1', 'zset2', 'zset0' into 'zset3'
  156. //Other parameters
  157. $redis->zunionstore('zset3',array('zset1','zset2'),array('weights' => array(5,0)));//The weights parameter represents the weight, which represents the union Elements with a final value greater than 5 are ranked first, and elements greater than 0 are ranked last
  158. $redis->zunionstore('zset3',array('zset1','zset2'),array('aggregate' => 'max' ));//'aggregate' => 'max' or 'min' indicates whether the same elements after union take a large value or a small value
  159. //zcount counts the number of elements in an index interval
  160. $redis ->zcount('zset1',3,5);//2
  161. $redis->zcount('zset1','(3',5)); //'(3' means the index value is in 3- Between 5 but not including 3, you can also use '(5' to indicate that the upper limit is 5 but not including 5
  162. //zcard counts the number of elements
  163. $redis->zcard('zset1');//4
  164. //zscore query the index of the element
  165. $redis->zscore('zset1','ef');//3
  166. //zremrangebyscore Delete elements in an index range
  167. $redis->zremrangebyscore('zset1',0,2); //Delete For elements with indexes between 0-2 ('ab', 'cd'), return the number of deleted elements 2
  168. //zrank/zrevrank returns the position of the element in table order/descending order (not the index)
  169. $redis-> ;zrank('zset1','ef');//Returns 0 because it is the first element; zrevrank returns 1 (the last one)
  170. //zremrangebyrank deletes the elements in the specified position range in the table
  171. $redis- >zremrangebyrank('zset1',0,10); //Delete elements at positions 0-10 and return the number of deleted elements 2
  172. /**
  173. hash table operation
  174. */
  175. //hset/hget access Data in hash table
  176. $redis->hset('hash1','key1','v1'); //Save elements with key 'key1' and value 'v1' into hash1 table
  177. $redis-> hset('hash1','key2','v2');
  178. $redis->hget('hash1','key1'); //Get the value of key 'key1' in table 'hash1' and return ' v1'
  179. //hexists Returns whether the specified key exists in the hash table
  180. $redis->hexists ('hash1','key1'); //true or false
  181. //hdel Delete the specified key in the hash table Element
  182. $redis->hdel('hash1','key2'); //true or false
  183. //hlen returns the number of hash table elements
  184. $redis->hlen('hash1'); //1
  185. //hsetnx adds an element, but cannot be repeated
  186. $redis->hsetnx('hash1','key1','v2'); //false
  187. $redis->hsetnx('hash1','key2 ','v2'); //true
  188. //hmset/hmget access multiple elements to the hash table
  189. $redis->hmset('hash1',array('key3'=>'v3',' key4'=>'v4'));
  190. $redis->hmget('hash1',array('key3','key4')); //Return the corresponding value array('v3','v4' )
  191. //hincrby accumulates the specified key
  192. $redis->hincrby('hash1','key5',3); //returns 3
  193. $redis->hincrby('hash1','key5', 10); //Return 13
  194. //hkeys Return all keys in the hash table
  195. $redis->hkeys('hash1'); //Return array('key1','key2','key3',' key4','key5')
  196. //hvals Returns all values ​​in the hash table
  197. $redis->hvals('hash1'); //Return array('v1','v2','v3',' v4',13)
  198. //hgetall returns the entire hash table element
  199. $redis->hgetall('hash1'); //returns array('key1'=>'v1','key2'=>' v2','key3'=>'v3','key4'=>'v4','key5'=>13)
  200. /**
  201. Sort operation
  202. */
  203. //sort sort
  204. $redis ->rpush('tab',3);
  205. $redis->rpush('tab',2);
  206. $redis->rpush('tab',17);
  207. $redis->sort( 'tab'); //Return array(2,3,17)
  208. //Using parameters, array('sort' => 'desc','limit' => array(1, 2)) can be used in combination
  209. $redis->sort('tab',array('sort' => 'desc')); //Arrange in descending order, return array(17,3,2)
  210. $redis->sort('tab ',array('limit' => array(1, 2))); //Return 2 elements of 1 in the sequential position (2 here refers to the number, not the position), return array(3,17 )
  211. $redis->sort('tab',array('limit' => array('alpha' => true))); // Sort by first character and return array(17,2,3), Because the first character of 17 is '1', it is ranked first
  212. $redis->sort('tab',array('limit' => array('store' => 'ordered'))); // Represents permanent sorting and returns the number of elements
  213. $redis->sort('tab',array('limit' => array('get' => 'pre_*'))); //Wildcards are used '*' filter element means only returning elements starting with 'pre_'
  214. /**
  215. redis management operations
  216. */
  217. //select specifies the database to be operated
  218. $redis->select('mydb'); / /Specify it as mydb, create it if it does not exist
  219. //flushdb clear the current library
  220. $redis->flushdb();
  221. //move move the elements of the current library to other libraries
  222. $redis->set('foo ', 'bar');
  223. $redis->move('foo', 'mydb2'); //If the 'mydb2' library exists
  224. //info displays the service status information
  225. $redis->info( ; //Clear the server
  226. //Save server data to disk synchronously
  227. $redis->save();
  228. //Save server data to disk asynchronously
  229. $redis->bgsave();
  230. //??
  231. $redis->bgrewriteaof();
  232. //Return the time when the disk was last updated
  233. $redis->lastsave();
  234. //set/get multiple key-values
  235. $mkv = array(
  236. 'usr: 0001' => 'First user',
  237. 'usr:0002' => 'Second user',
  238. 'usr:0003' => 'Third user'
  239. );
  240. $redis->mset($mkv ); //Storage values ​​corresponding to multiple keys
  241. $retval = $redis->mget(array_keys($mkv)); //Get values ​​corresponding to multiple keys
  242. print_r($retval);
  243. //Batch Operation
  244. $replies = $redis->pipeline(function($pipe) {
  245. $pipe->ping();
  246. $pipe->flushdb();
  247. $pipe->incrby('counter', 10); //Increment operation
  248. $pipe->incrby('counter', 30);
  249. $pipe->exists('counter');
  250. $pipe->get('counter');
  251. $pipe->mget('does_not_exist', 'counter');
  252. });
  253. print_r($replies);
  254. //CAS,事务性操作
  255. function zpop($client, $zsetKey) {
  256. $element = null;
  257. $options = array(
  258. 'cas' => true, // Initialize with support for CAS operations
  259. 'watch' => $zsetKey, // Key that needs to be WATCHed to detect changes
  260. 'retry' => 3, // Number of retries on aborted transactions, after
  261. // which the client bails out with an exception.
  262. );
  263. $txReply = $client->multiExec($options, function($tx)
  264. use ($zsetKey, &$element) {
  265. @list($element) = $tx->zrange($zsetKey, 0, 0);
  266. if (isset($element)) {
  267. $tx->multi(); // With CAS, MULTI *must* be explicitly invoked.
  268. $tx->zrem($zsetKey, $element);
  269. }
  270. });
  271. return $element;
  272. }
  273. $zpopped = zpop($redis, 'zset');
  274. echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "n";
  275. //对存取的key加前缀,如: 'nrk:'
  276. $redis->getProfile()->setPreprocessor(new KeyPrefixPreprocessor('nrk:'));
  277. //分布式存储的一些方法
  278. $multiple_servers = array(
  279. array(
  280. 'host' => '127.0.0.1',
  281. 'port' => 6379,
  282. 'database' => 15,
  283. 'alias' => 'first',
  284. ),
  285. array(
  286. 'host' => '127.0.0.1',
  287. 'port' => 6380,
  288. 'database' => 15,
  289. 'alias' => 'second',
  290. ),
  291. );
  292. use PredisDistributionIDistributionStrategy;
  293. class NaiveDistributionStrategy implements IDistributionStrategy {
  294. private $_nodes, $_nodesCount;
  295. public function __constructor() {
  296. $this->_nodes = array();
  297. $this->_nodesCount = 0;
  298. }
  299. public function add($node, $weight = null) {
  300. $this->_nodes[] = $node;
  301. $this->_nodesCount++;
  302. }
  303. public function remove($node) {
  304. $this->_nodes = array_filter($this->_nodes, function($n) use($node) {
  305. return $n !== $node;
  306. });
  307. $this->_nodesCount = count($this->_nodes);
  308. }
  309. public function get($key) {
  310. $count = $this->_nodesCount;
  311. if ($count === 0) {
  312. throw new RuntimeException('No connections');
  313. }
  314. return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
  315. }
  316. public function generateKey($value) {
  317. return crc32($value);
  318. }
  319. }
  320. //配置键分布策略
  321. $options = array(
  322. 'key_distribution' => new NaiveDistributionStrategy(),
  323. );
  324. $redis = new PredisClient($multiple_servers, $options);
  325. for ($i = 0; $i set("key:$i", str_pad($i, 4, '0', 0));
  326. $redis->get("key:$i");
  327. }
  328. $server1 = $redis->getClientFor('first')->info();
  329. $server2 = $redis->getClientFor('second')->info();
  330. printf("Server '%s' has %d keys while server '%s' has %d keys.n",
  331. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  332. );
复制代码

php, redis, predis
本主题由 小贝 于 2015-11-12 08:43 移动


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template