Php connection to redis database predis operations Daquan

Source: Internet
Author: User
Tags crc32
Php connection to redis database predis operations Daquan

Predis is the php database for connecting to redis. because it is fully written in php and uses a lot of namespace and closure functions, it only supports php5.3 and later versions, so the test performance is normal, 25000 reads/writes per second, I believe that the performance of php extensions written in C language will be significantly improved (for example, using C extension phpredis https://github.com/owlient/phpredis ).

It is also easy to store session data in redis:
Session. save_handler = redis
Session. save_path = "tcp: // 127.0.0.1: 6379 ″

Below are some operations summarized and updated continuously.

  1. // Use autoload to load the relevant database. 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 connected IP address, port, and database
  10. $ Server = array (
  11. 'Host' => '2017. 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; // Display 'predis'
  20. // Setex set a storage validity period
  21. $ Redis-> setex ('str', 10, 'bar'); // indicates that the storage is valid for 10 seconds.
  22. // Setnx/msetnx is equivalent to the add operation and does not overwrite existing values.
  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); // 34 is returned.
  27. // Incrby/incr/decrby/decr increment and decrease
  28. $ Redis-> incr ('Foo'); // foo is 57
  29. $ Redis-> incrby ('foo', 2); // foo is 59
  30. // Exists checks whether a value exists.
  31. $ Redis-> exists ('Foo'); // true
  32. // Delete del
  33. $ Redis-> del ('Foo'); // true
  34. // Type detection, string return string, list return list, set table return set/zset, hash table return hash
  35. $ Redis-> type ('Foo'); // if no value exists, none is returned.
  36. $ Redis-> set ('str', 'test ');
  37. $ Redis-> type ('str'); // string, return string
  38. // Append connection to an existing string
  39. $ Redis-> append ('str', '_ 100'); // return the accumulated string length of 8. the str value is 'test _ 100'
  40. // Setrange partial replacement
  41. $ Redis-> setrange ('str', 0, 'ABC'); // returns 3. if parameter 2 is 0, it is equivalent to the set operation.
  42. $ Redis-> setrange ('str', 2, 'CD'); // returns 4, which indicates that the value is replaced after 2nd characters. then, 'str' is 'ABCD'
  43. // Substr partial acquisition operation
  44. $ Redis-> substr ('str', 0th); // it indicates that it starts from 2nd and takes characters, 3 in total. 'ABC' is returned'
  45. // Obtain the string length by strlen
  46. $ Redis-> strlen ('str'); // 4 is returned.
  47. // Setbit/getbit storage and retrieval
  48. $ Redis-> setbit ('binary ', 31,1); // indicates storing 1 in 31st bits. Is there a problem with the size? But it doesn't matter. getbit should be okay.
  49. $ Redis-> getbit ('binary ', 31); // return 1
  50. // The keys fuzzy search function supports the * and? (Match one character)
  51. $ Redis-> set ('foo1', 123 );
  52. $ Redis-> set ('foo2', 456 );
  53. $ Redis-> keys ('foo * '); // returns the array of foo1 and foo2
  54. $ Redis-> keys ('F? O? '); // Same as above
  55. // Randomkey returns a random key
  56. $ Redis-> randomkey (); // it may return 'foo1' or 'foo2' and any other key with redis
  57. // Rename/renamenx rename the key. The difference is that renamenx cannot be changed to an existing key.
  58. $ Redis-> rename ('str', 'str2'); // change the key originally named 'str' to 'str2'
  59. // Expire sets the key-value validity period, ttl gets the remaining validity period, and persist is reset to permanent storage.
  60. $ Redis-> expire ('foo', 1); // Set the validity period to 1 second.
  61. $ Redis-> ttl ('Foo'); // returns the validity period of 1 s.
  62. $ Redis-> expire ('Foo'); // cancel the expire action
  63. // Dbsize returns the total number of records of the current redis database
  64. $ Redis-> dbsize ();
  65. /*
  66. Queue operations
  67. */
  68. // Rpush/rpushx ordered list operation, insert elements from the queue
  69. // The difference between lpush/lpushx and rpush/rpushx is that it is inserted into the queue header. the same as above, 'x' indicates that only the existing key is operated.
  70. $ Redis-> rpush ('foolist', 'bar1'); // return the length of a list of 1
  71. $ Redis-> lpush ('foolist', 'bar0'); // returns the length of a list of 2
  72. $ Redis-> rpushx ('foolist', 'bar2'); // return 3. rpushx only adds existing queues; otherwise, 0 is returned.
  73. // Llen returns the length of the current list
  74. $ Redis-> llen ('foolist'); // 3
  75. // Lrange returns the element of a range in the queue.
  76. $ Redis-> lrange ('foolist', 0th); // The Returned array contains 1st to elements in total.
  77. $ Redis-> lrange ('foolist', 0,-1); // returns the first to the last, which is equivalent to returning all elements. Note that a negative number is often used in redis, same below
  78. // Lindex returns the list element at the specified sequence.
  79. $ Redis-> lindex ('foolist', 1); // return 'bar1'
  80. // Lset modifies the value at the specified position in the queue
  81. $ Redis-> lset ('foolist', 1, '20140901'); // modify the element at location 1 and return true
  82. // Lrem deletes the specified number of characters from the left of the queue.
  83. $ Redis-> lrem ('foolist', 1, '_'); // delete the left of the queue (use-1 from the right) 1 Character '_' (if any)
  84. // Lpop/rpop pops up (and deletes) the leftmost or rightmost element similar to the stack structure.
  85. $ Redis-> lpop ('foolist'); // 'bar0'
  86. $ Redis-> rpop ('foolist'); // 'bar2'
  87. // Modify the ltrim queue, retain several elements on the left, and delete the remaining elements.
  88. $ Redis-> ltrim ('foolist', 0th); // retain 1st to elements on the left
  89. // Rpoplpush outputs elements from one queue pop 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'); // It is also applicable to the same queue. move the last element to the header list2 => array ('ab3 ', 'ab1', 'ab2 ')
  96. // Linsert inserts an element before or after the specified element in the queue
  97. $ Redis-> linsert ('list2', 'before', 'ab1', '123'); // inserts '123456' before the 'ab1' element'
  98. $ Redis-> linsert ('list2', 'after', 'ab1', '123'); // inserts '123456' after the element 'ab1'
  99. // Blpop/brpop blocking and waiting for a queue not empty, pop out the leftmost or rightmost element (this function can be very useful outside php)
  100. // Brpoplpush is also blocked and waits for the operation. The result is the same as rpoplpush.
  101. $ Redis-> blpop ('list3', 10); // If list3 is empty, wait until the first element pops up when it is not empty and times out after 10 seconds
  102. /**
  103. Set Table operations
  104. */
  105. // Add an element to sadd. true is returned. false is returned for repeated operations.
  106. $ Redis-> sadd ('set1', 'AB ');
  107. $ Redis-> sadd ('set1', 'CD ');
  108. $ Redis-> sadd ('set1', 'ef ');
  109. // Srem removes the specified element
  110. $ Redis-> srem ('set1', 'CD'); // delete the 'CD' element
  111. // Spop pops up the first element
  112. $ Redis-> spop ('set1 ');
  113. // Smove moves 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' from 'set1' to 'set2', and return true or false
  116. // Scard returns the number of elements in the current set table
  117. $ Redis-> scard ('set2'); // 2
  118. // Sismember determines whether the element belongs to the current table
  119. $ Redis-> sismember ('set2', '20140901'); // true or false
  120. // Smembers returns all elements of the current table
  121. $ Redis-> smembers ('set2'); // array ('20140901', 'AB ');
  122. // Sinter/sunion/sdiff returns the intersection of elements in the two tables/Union/complement set
  123. $ Redis-> sadd ('set1', 'AB ');
  124. $ Redis-> sinter ('set2', 'set1'); // returns array ('AB ')
  125. // Sinterstore/sunionstore/sdiffstore copy the intersection/Union/complementary set 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 content of 'set1' to 'foo, convert 'foo' to the set table.
  128. $ Redis-> sinterstore ('foo', array ('set1', 'set2 ')); // copy the same elements in 'set1' and 'set2' to the 'foo' table to overwrite 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. // Add an element to sadd and set the sequence number. true is returned. false is returned if the number is repeated.
  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 a specified element and changes the order of elements
  139. $ Redis-> zincrby ('zset1', 10, 'AB'); // return 11
  140. // Zrem remove the specified element
  141. $ Redis-> zrem ('zset1', 'ef '); // true or false
  142. // Zrange returns the elements of the specified range in the table in order of position
  143. $ Redis-> zrange ('zset1',); // returns an element between 0 and 1.
  144. $ Redis-> zrange ('zset1', 0,-1); // returns the element between position 0 and the last element (equivalent to all elements)
  145. // Zrevrange is the same as above. Elements of the specified range in the table are returned in reverse order.
  146. $ Redis-> zrevrange ('zset1', 0,-1); // The element sequence is opposite to zrange.
  147. // Zrangebyscore/zrevrangebyscore returns the elements of the specified index range in the table in order/in descending order.
  148. $ Redis-> zadd ('zset1', 3, 'ef ');
  149. $ Redis-> zadd ('zset1', 5, 'gh ');
  150. $ Redis-> zrangebyscore ('zset1',); // returns the array ('ef ', 'gh') element between 2-9 index values ')
  151. // Parameter format
  152. $ Redis-> zrangebyscore ('zset1', 'withscores'); // returns the elements between the index value and the index value array ('ef ', 3), array ('GH', 5 ))
  153. $ Redis-> zrangebyscore ('zset1', array ('withscores' => true, 'limit' => array (1, 2 ))); // return the elements between the index value and 2-9. 'withscores' => true indicates that the index value is included; 'limit' => array (1, 2) indicates that up to 2 items are returned, the result is 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'); // Set 'zset1', 'zset2 ', the Union of 'zset0' is stored in 'zset3'
  156. // Other parameters
  157. $ Redis-> zunionstore ('zset3', array ('zset1', 'zset2'), array ('weight' => array (5, 0 ))); // The weights parameter indicates the weight, which indicates that elements with a union value greater than 5 are ranked first, and those with a value greater than 0 are ranked later.
  158. $ Redis-> zunionstore ('zset3', array ('zset1', 'zset2'), array ('aggregat' => 'Max ')); // 'aggregate' => 'Max 'or 'min' indicates that the same element after the union is used to take the Iterator or a small value.
  159. // Zcount counts the number of elements in an index range.
  160. $ Redis-> zcount ('zset1', 3,5); // 2
  161. $ Redis-> zcount ('zset1', '(3', 5); //' (3' indicates that the index value ranges from 3 to 5, but does not include 3, you can also use '(5' to indicate the upper limit is 5 but not 5.
  162. // Zcard count
  163. $ Redis-> zcard ('zset1'); // 4
  164. // Index of the zscore query element
  165. $ Redis-> zscore ('zset1', 'ef '); // 3
  166. // Zremrangebyscore deletes the element of an index range.
  167. $ Redis-> zremrangebyscore ('zset1',); // delete the elements between 0-2 ('AB', 'CD'), and return the number of deleted elements 2
  168. // Zrank/zrevrank returns the order of the table in which the elements are located/the position in descending order (not an 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',); // delete an element with a position of 0 to 10. the number of deleted elements is 2.
  172. /**
  173. Hash table operations
  174. */
  175. // Hset/hget to access the data in the hash table
  176. $ Redis-> hset ('hash1', 'key1', 'v1 '); // store the elements whose key is 'key1' value is 'v1' to the hash1 table.
  177. $ Redis-> hset ('hash1', 'key2', 'V2 ');
  178. $ Redis-> hget ('hash1', 'key1'); // retrieves the value of key 'key1' in 'hash1' and returns 'V1'
  179. // Hexists returns whether the specified key in the hash table exists
  180. $ Redis-> hexists ('hash1', 'key1'); // true or false
  181. // Hdel delete the elements of the specified key in the hash table
  182. $ Redis-> hdel ('hash1', 'key2'); // true or false
  183. // Hlen returns the number of hash table elements
  184. $ Redis-> hlen ('hash1'); // 1
  185. // Add an element to hsetnx, but it cannot be repeated.
  186. $ Redis-> hsetnx ('hash1', 'key1', 'V2'); // false
  187. $ Redis-> hsetnx ('hash1', 'key2', 'V2'); // true
  188. // Hmset/HMET access multiple elements to the hash table
  189. $ Redis-> hmset ('hash1', array ('key3' => 'v3 ', 'key4' => 'V4 '));
  190. $ Redis-> HMET ('hash1', array ('key3', 'key4'); // returns the corresponding value array ('v3 ', 'V4 ')
  191. // Hincrby accumulates the specified key
  192. $ Redis-> hincrby ('hash1', 'key5', 3); // 3 is returned.
  193. $ Redis-> hincrby ('hash1', 'key5', 10); // return 13
  194. // Hkeys returns 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
  204. $ Redis-> rpush ('Tab ', 3 );
  205. $ Redis-> rpush ('Tab ', 2 );
  206. $ Redis-> rpush ('Tab ', 17 );
  207. $ Redis-> sort ('Tab '); // returns array (2, 3, 17)
  208. // Use parameters. you can use array ('sort '=> 'desc', 'Limit' => array (1, 2) in combination ))
  209. $ Redis-> sort ('Tab ', array ('sort' => 'desc'); // returns array (, 2) in descending order)
  210. $ Redis-> sort ('Tab ', array ('limit' => array (1, 2 ))); // returns two elements of 1 in the ordered position (2 here refers to the number, not the position), and returns array)
  211. $ Redis-> sort ('Tab ', array ('limit' => array ('alpha' => true); // returns array (17,2, 3) because the first character of 17 is '1 ',
  212. $ Redis-> sort ('Tab ', array ('limit' => array ('store' => 'ordered'); // indicates permanent sorting and returns the number of elements.
  213. $ Redis-> sort ('Tab ', array ('limit' => array ('get' => 'pre _*'))); // use the wildcard '*' to filter elements, indicating that only elements starting with 'pre _ 'are returned.
  214. /**
  215. Redis management operations
  216. */
  217. // Select specifies the database to operate
  218. $ Redis-> select ('mydb'); // it is specified as mydb. if it does not exist, it is created.
  219. // Flushdb clears the current database
  220. $ Redis-> flushdb ();
  221. // Move the elements of the database to other databases
  222. $ Redis-> set ('foo', 'bar ');
  223. $ Redis-> move ('foo', 'mydb'); // If 'mydb' is in stock
  224. // Info displays service status information
  225. $ Redis-> info ();
  226. // Slaveof configuration slave server
  227. $ Redis-> slaveof ('127. 0.0.1 ', 80); // The server configured with Port 80 127.0.0.1 is a slave server
  228. $ Redis-> slaveof (); // clear the slave server
  229. // Synchronously save server data to disk
  230. $ Redis-> save ();
  231. // Asynchronously save server data to disk
  232. $ Redis-> bgsave ();
  233. //??
  234. $ Redis-> bgrewriteaof ();
  235. // Returns the last disk update time.
  236. $ Redis-> lastsave ();
  237. // Set/get multiple key-values
  238. $ Mkv = array (
  239. 'Usr: 100' => 'first user ',
  240. 'Usr: 100' => 'seconduser ',
  241. 'Usr: 000000' => 'third user'
  242. );
  243. $ Redis-> mset ($ mkv); // store values corresponding to multiple keys
  244. $ Retval = $ redis-> mget (array_keys ($ mkv); // obtain the value corresponding to multiple keys
  245. Print_r ($ retval );
  246. // Batch operation
  247. $ Replies = $ redis-> pipeline (function ($ pipe ){
  248. $ Pipe-> ping ();
  249. $ Pipe-> flushdb ();
  250. $ Pipe-> incrby ('counter', 10); // incremental operation
  251. $ Pipe-> incrby ('counter', 30 );
  252. $ Pipe-> exists ('counter ');
  253. $ Pipe-> get ('counter ');
  254. $ Pipe-> mget ('does _ not_exist ', 'counter ');
  255. });
  256. Print_r ($ replies );
  257. // CAS, transactional operations
  258. Function zpop ($ client, $ zsetKey ){
  259. $ Element = null;
  260. $ Options = array (
  261. 'Cas '=> true, // Initialize with support for cas operations
  262. 'Watch '=> $ zsetKey, // Key that needs to be WATCHed to detect changes
  263. 'Retry' => 3, // Number of retries on aborted transactions, after
  264. // Which the client bails out with an exception.
  265. );
  266. $ TxReply = $ client-> multiExec ($ options, function ($ tx)
  267. Use ($ zsetKey, & $ element ){
  268. @ List ($ element) = $ tx-> zrange ($ zsetKey, 0, 0 );
  269. If (isset ($ element )){
  270. $ Tx-> multi (); // With CAS, MULTI * must * be explicitly invoked.
  271. $ Tx-> zrem ($ zsetKey, $ element );
  272. }
  273. });
  274. Return $ element;
  275. }
  276. $ Zpopped = zpop ($ redis, 'zset ');
  277. Echo isset ($ zpopped )? "ZPOPed $ zpopped": "Nothing to ZPOP! "," \ N ";
  278. // Add a prefix to the access key, for example, 'nrk :'
  279. $ Redis-> getProfile ()-> setPreprocessor (new KeyPrefixPreprocessor ('nrk :'));
  280. // Some distributed storage methods
  281. $ Multiple_servers = array (
  282. Array (
  283. 'Host' => '2017. 0.0.1 ',
  284. 'Port' => 6379,
  285. 'Database' => 15,
  286. 'Alias' => 'first ',
  287. ),
  288. Array (
  289. 'Host' => '2017. 0.0.1 ',
  290. 'Port' => 6380,
  291. 'Database' => 15,
  292. 'Alias' => 'second ',
  293. ),
  294. );
  295. Use Predis \ Distribution \ IDistributionStrategy;
  296. Class NaiveDistributionStrategy implements IDistributionStrategy {
  297. Private $ _ nodes, $ _ nodesCount;
  298. Public function _ constructor (){
  299. $ This-> _ nodes = array ();
  300. $ This-> _ nodesCount = 0;
  301. }
  302. Public function add ($ node, $ weight = null ){
  303. $ This-> _ nodes [] = $ node;
  304. $ This-> _ nodesCount ++;
  305. }
  306. Public function remove ($ node ){
  307. $ This-> _ nodes = array_filter ($ this-> _ nodes, function ($ n) use ($ node ){
  308. Return $ n! = $ Node;
  309. });
  310. $ This-> _ nodesCount = count ($ this-> _ nodes );
  311. }
  312. Public function get ($ key ){
  313. $ Count = $ this-> _ nodesCount;
  314. If ($ count = 0 ){
  315. Throw new RuntimeException ('no connections ');
  316. }
  317. Return $ this-> _ nodes [$ count> 1? Abs (crc32 ($ key) % $ count): 0];
  318. }
  319. Public function generateKey ($ value ){
  320. Return crc32 ($ value );
  321. }
  322. }
  323. // Configure the key distribution policy
  324. $ Options = array (
  325. 'Key _ distribution '=> new NaiveDistributionStrategy (),
  326. );
  327. $ Redis = new Predis \ Client ($ multiple_servers, $ options );
  328. For ($ I = 0; $ I set ("key: $ I", str_pad ($ I, 4, '0', 0 ));
  329. $ Redis-> get ("key: $ I ");
  330. }
  331. $ Server1 = $ redis-> getClientFor ('first')-> info ();
  332. $ Server2 = $ redis-> getClientFor ('second')-> info ();
  333. Printf ("Server '% s' has % d keys while server' % s' has % d keys. \ n ",
  334. 'First', $ server1 ['db15'] ['Keys '], 'second', $ server2 ['db15'] ['Keys']
  335. );


Php, redis, predis

This topic was moved by Beckham

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.