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.
- //Use autoload to load related libraries. The focus here is to require $file;
- spl_autoload_register(function($class) {
- $file = __DIR__.'/lib/Predis/'.$class.'.php ';
- if (file_exists($file)) {
- require $file;
- return true;
- }
- });
-
- //Configure the connection IP, port, and corresponding database
- $server = array(
- 'host' => '127.0.0.1',
- 'port' => 6379,
- 'database' = > 15
- );
- $redis = new Client($server);
-
- //Normal set/get operation
- $redis->set('library', 'predis');
- $retval = $redis- >get('library');
- echo $retval; //Show 'predis'
-
- //setex set a storage time limit
- $redis->setex('str', 10, 'bar'); // Indicates that the storage validity period is 10 seconds
-
- //setnx/msetnx is equivalent to the add operation and will not overwrite the existing value
- $redis->setnx('foo',12); //true
- $redis->setnx( 'foo',34); //false
-
- //getset operation, a variant of set, the result returns the value before replacement
- $redis->getset('foo',56);//returns 34
-
- // incrby/incr/decrby/decr Increment and decrement the value
- $redis->incr('foo'); //foo is 57
- $redis->incrby('foo',2); //foo is 59
-
- //exists detects whether a certain value exists
- $redis->exists('foo');//true
-
- //del deletes
- $redis->del('foo');//true
-
- //type type detection, string returns string, list returns list, set table returns set/zset, hash table returns hash
- $redis->type('foo');//does not exist, returns none
- $redis ->set('str','test');
- $redis->type('str'); //String, return string
-
- //Append connect to the existing string
- $redis-> ;append('str','_123'); //Return the accumulated string length 8, this time str is 'test_123'
-
- //setrange partial replacement operation
- $redis->setrange('str', 0,'abc'); //Return 3, when parameter 2 is 0, it is equivalent to the set operation
- $redis->setrange('str',2,'cd');//Return 4, which means starting from the second Replace after the character, then 'str' is 'abcd'
-
- //substr part of the acquisition operation
- $redis->substr('str',0,2);//means starting from the 0th, get to the 0th 2 characters, 3 in total, return 'abc'
-
- //strlen Get the string length
- $redis->strlen('str'); //Return 4
-
- //setbit/getbit bit storage and acquisition
- $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.
- $redis-> ;getbit('binary',31); //return 1
-
- //keys fuzzy search function, supports * sign and ? sign (match one character)
- $redis->set('foo1',123);
- $redis->set('foo2',456);
- $redis->keys('foo*'); //Return the array of foo1 and foo2
- $redis->keys('f?o?' ); //Same as above
-
- //randomkey randomly returns a key
- $redis->randomkey(); //It may return 'foo1' or 'foo2' or any other key that exists in redis
-
- //rename /renamenx Rename the key. The difference is that renamenx does not allow changing to an existing key
- $redis->rename('str','str2'); //Change the key originally named 'str' to 'str2'
-
- //expire sets the timeliness of key-value, ttl gets the remaining validity period, persist is reset to permanent storage
- $redis->expire('foo', 1); //Set the validity period to 1 second
- $redis->ttl('foo'); //Return the validity period value 1s
- $redis->expire('foo'); //Cancel the expire behavior
-
- //dbsize Returns the total number of records in the current redis database
- $redis->dbsize();
-
- /*
- Queue operation
- */
-
- //rpush/rpushx Ordered list operation, insert elements from the queue
- //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
- $redis->rpush('fooList', 'bar1'); //Return a list of length 1
- $redis- >lpush('fooList', 'bar0'); //Returns the length of a list 2
- $redis->rpushx('fooList', 'bar2'); //Returns 3, rpushx only works on existing queues Add, otherwise return 0
- //llen returns the current list length
- $redis->llen('fooList');//3
-
- //lrange returns the elements of a range in the queue
- $redis->lrange( 'fooList',0,1); //The returned array contains a total of 2 elements from the 0th to the 1st
- $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
-
- //lindex returns the list elements at the specified sequence position
- $redis->lindex('fooList',1); //Return 'bar1'
-
- //lset Modify the value at the specified position in the queue
- $redis->lset('fooList',1,'123');//Modify the element at position 1 and return true
-
- / /lrem Delete the specified number of characters from the left in the queue
- $redis->lrem('fooList',1,'_'); //Delete 1 character '_' from the left (use -1 from the right) in the queue (if any)
-
- //lpop/rpop pops (and deletes) the leftmost or rightmost element similar to a stack structure
- $redis->lpop('fooList'); //'bar0'
- $redis- >rpop('fooList'); //'bar2'
-
- //ltrim Queue modification, keep a few elements from the left, delete the rest
- $redis->ltrim('fooList', 0,1); //Keep The 0th to 1st elements from the left
-
- //rpoplpush pops elements from one queue and pushes them to another queue
- $redis->rpush('list1','ab0');
- $redis-> ;rpush('list1','ab1');
- $redis->rpush('list2','ab2');
- $redis->rpush('list2','ab3');
- $redis->rpoplpush('list1','list2');//Result list1 =>array('ab0'),list2 =>array('ab1','ab2','ab3')
- $ redis->rpoplpush('list2','list2');//Also applies to the same queue, move the last element to the head list2 =>array('ab3','ab1','ab2')
-
- //linsert inserts elements before or after the specified element in the middle of the queue
- $redis->linsert('list2', 'before','ab1','123'); //Indicates before element 'ab1' Insert '123'
- $redis->linsert('list2', 'after','ab1','456'); //Indicates inserting '456' after element 'ab1'
-
- //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)
- //brpoplpush also blocks and waits for the operation, and the result is the same as rpoplpush
- $redis ->blpop('list3',10); //If list3 is empty, wait until the first element is popped when it is not empty. Timeout after 10 seconds
-
- /**
- set table operation
- */
-
- / /sadd adds elements, returns true, returns false repeatedly
- $redis->sadd('set1','ab');
- $redis->sadd('set1','cd');
- $redis-> ;sadd('set1','ef');
-
- //srem Remove the specified element
- $redis->srem('set1','cd'); //Delete the 'cd' element
-
- //spop Pop the first element
- $redis->spop('set1');
-
- //smove Move the specified element of the current set table to another set table
- $redis->sadd('set2','123');
- $redis->smove('set1','set2','ab');//Move 'ab' in 'set1' to 'set2', return true or false
-
- //scard returns the current set table Number of elements
- $redis->scard('set2');//2
-
- //sismember Determine whether the element belongs to the current table
- $redis->sismember('set2','123'); //true or false
-
- //smembers returns all elements of the current table
- $redis->smembers('set2'); //array('123','ab');
-
- //sinter/sunion/sdiff returns two The intersection/union/complement of the elements in the table
- $redis->sadd('set1','ab');
- $redis->sinter('set2','set1'); //return array ('ab')
-
- //sinterstore/sunionstore/sdiffstore Copy the intersection/union/complement elements of the two tables to the third table
- $redis->set('foo',0);
- $ redis->sinterstore('foo','set1'); //This is equivalent to copying the contents of 'set1' to 'foo' and converting 'foo' to a set table
- $redis->sinterstore ('foo',array('set1','set2')); //Copy the same elements in 'set1' and 'set2' to the 'foo' table, overwriting the original content of 'foo'
-
- // srandmember returns a random element in the table
- $redis->srandmember('set1');
-
- /**
- Ordered set table operation
- */
-
- //sadd adds an element and sets the serial number, returns true, and returns false repeatedly
- $ redis->zadd('zset1',1,'ab');
- $redis->zadd('zset1',2,'cd');
- $redis->zadd('zset1',3, 'ef');
-
- //zincrby increases or decreases the index value of the specified element and changes the order of the elements
- $redis->zincrby('zset1',10,'ab');//returns 11
-
- // zrem removes the specified element
- $redis->zrem('zset1','ef'); //true or false
-
- //zrange returns the elements in the specified range in the table in position order
- $redis->zrange( 'zset1',0,1); //Return the elements between positions 0 and 1 (two)
- $redis->zrange('zset1',0,-1); //Return the position 0 and the last one Elements between one element (equivalent to all elements)
-
- //zrevrange Same as above, returns the elements in the specified range in the table, in reverse order
- $redis->zrevrange('zset1',0,-1); //The order of elements is opposite to zrange
-
- //zrangebyscore/zrevrangebyscore returns the elements of the specified index range in the table in order/descending order
- $redis->zadd('zset1',3,'ef');
- $redis-> ;zadd('zset1',5,'gh');
- $redis->zrangebyscore('zset1',2,9); //Return elements array('ef',' between index values 2-9 gh')
- //Parameter form
- $redis->zrangebyscore('zset1',2,9,'withscores'); //Return elements between index values 2-9 and contain index values array(array(' ef',3),array('gh',5))
- $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))
-
- //zunionstore/zinterstore Store the union/intersection of multiple tables into another table
- $redis-> zunionstore('zset3',array('zset1','zset2','zset0')); //Save the union of 'zset1', 'zset2', 'zset0' into 'zset3'
- //Other parameters
- $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
- $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
-
- //zcount counts the number of elements in an index interval
- $redis ->zcount('zset1',3,5);//2
- $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
-
- //zcard counts the number of elements
- $redis->zcard('zset1');//4
-
- //zscore query the index of the element
- $redis->zscore('zset1','ef');//3
-
- //zremrangebyscore Delete elements in an index range
- $redis->zremrangebyscore('zset1',0,2); //Delete For elements with indexes between 0-2 ('ab', 'cd'), return the number of deleted elements 2
-
- //zrank/zrevrank returns the position of the element in table order/descending order (not the index)
- $redis-> ;zrank('zset1','ef');//Returns 0 because it is the first element; zrevrank returns 1 (the last one)
-
- //zremrangebyrank deletes the elements in the specified position range in the table
- $redis- >zremrangebyrank('zset1',0,10); //Delete elements at positions 0-10 and return the number of deleted elements 2
-
- /**
- hash table operation
- */
-
- //hset/hget access Data in hash table
- $redis->hset('hash1','key1','v1'); //Save elements with key 'key1' and value 'v1' into hash1 table
- $redis-> hset('hash1','key2','v2');
- $redis->hget('hash1','key1'); //Get the value of key 'key1' in table 'hash1' and return ' v1'
-
- //hexists Returns whether the specified key exists in the hash table
- $redis->hexists ('hash1','key1'); //true or false
-
- //hdel Delete the specified key in the hash table Element
- $redis->hdel('hash1','key2'); //true or false
-
- //hlen returns the number of hash table elements
- $redis->hlen('hash1'); //1
-
- //hsetnx adds an element, but cannot be repeated
- $redis->hsetnx('hash1','key1','v2'); //false
- $redis->hsetnx('hash1','key2 ','v2'); //true
-
- //hmset/hmget access multiple elements to the hash table
- $redis->hmset('hash1',array('key3'=>'v3',' key4'=>'v4'));
- $redis->hmget('hash1',array('key3','key4')); //Return the corresponding value array('v3','v4' )
-
- //hincrby accumulates the specified key
- $redis->hincrby('hash1','key5',3); //returns 3
- $redis->hincrby('hash1','key5', 10); //Return 13
-
- //hkeys Return all keys in the hash table
- $redis->hkeys('hash1'); //Return array('key1','key2','key3',' key4','key5')
-
- //hvals Returns all values in the hash table
- $redis->hvals('hash1'); //Return array('v1','v2','v3',' v4',13)
-
- //hgetall returns the entire hash table element
- $redis->hgetall('hash1'); //returns array('key1'=>'v1','key2'=>' v2','key3'=>'v3','key4'=>'v4','key5'=>13)
-
- /**
- Sort operation
- */
-
- //sort sort
- $redis ->rpush('tab',3);
- $redis->rpush('tab',2);
- $redis->rpush('tab',17);
- $redis->sort( 'tab'); //Return array(2,3,17)
- //Using parameters, array('sort' => 'desc','limit' => array(1, 2)) can be used in combination
- $redis->sort('tab',array('sort' => 'desc')); //Arrange in descending order, return array(17,3,2)
- $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 )
- $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
- $redis->sort('tab',array('limit' => array('store' => 'ordered'))); // Represents permanent sorting and returns the number of elements
- $redis->sort('tab',array('limit' => array('get' => 'pre_*'))); //Wildcards are used '*' filter element means only returning elements starting with 'pre_'
-
- /**
- redis management operations
- */
-
- //select specifies the database to be operated
- $redis->select('mydb'); / /Specify it as mydb, create it if it does not exist
-
- //flushdb clear the current library
- $redis->flushdb();
-
- //move move the elements of the current library to other libraries
- $redis->set('foo ', 'bar');
- $redis->move('foo', 'mydb2'); //If the 'mydb2' library exists
-
- //info displays the service status information
- $redis->info( ; //Clear the server
-
- //Save server data to disk synchronously
- $redis->save();
- //Save server data to disk asynchronously
- $redis->bgsave();
- //??
- $redis->bgrewriteaof();
- //Return the time when the disk was last updated
- $redis->lastsave();
-
- //set/get multiple key-values
- $mkv = array(
- 'usr: 0001' => 'First user',
- 'usr:0002' => 'Second user',
- 'usr:0003' => 'Third user'
- );
- $redis->mset($mkv ); //Storage values corresponding to multiple keys
- $retval = $redis->mget(array_keys($mkv)); //Get values corresponding to multiple keys
- print_r($retval);
-
- //Batch Operation
- $replies = $redis->pipeline(function($pipe) {
- $pipe->ping();
- $pipe->flushdb();
- $pipe->incrby('counter', 10); //Increment operation
- $pipe->incrby('counter', 30);
- $pipe->exists('counter');
- $pipe->get('counter');
- $pipe->mget('does_not_exist', 'counter');
- });
- print_r($replies);
-
- //CAS,事务性操作
-
- function zpop($client, $zsetKey) {
- $element = null;
- $options = array(
- 'cas' => true, // Initialize with support for CAS operations
- 'watch' => $zsetKey, // Key that needs to be WATCHed to detect changes
- 'retry' => 3, // Number of retries on aborted transactions, after
- // which the client bails out with an exception.
- );
-
- $txReply = $client->multiExec($options, function($tx)
- use ($zsetKey, &$element) {
- @list($element) = $tx->zrange($zsetKey, 0, 0);
- if (isset($element)) {
- $tx->multi(); // With CAS, MULTI *must* be explicitly invoked.
- $tx->zrem($zsetKey, $element);
- }
- });
- return $element;
- }
- $zpopped = zpop($redis, 'zset');
- echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "n";
-
- //对存取的key加前缀,如: 'nrk:'
- $redis->getProfile()->setPreprocessor(new KeyPrefixPreprocessor('nrk:'));
-
- //分布式存储的一些方法
- $multiple_servers = array(
- array(
- 'host' => '127.0.0.1',
- 'port' => 6379,
- 'database' => 15,
- 'alias' => 'first',
- ),
- array(
- 'host' => '127.0.0.1',
- 'port' => 6380,
- 'database' => 15,
- 'alias' => 'second',
- ),
- );
-
- use PredisDistributionIDistributionStrategy;
-
- class NaiveDistributionStrategy implements IDistributionStrategy {
- private $_nodes, $_nodesCount;
-
- public function __constructor() {
- $this->_nodes = array();
- $this->_nodesCount = 0;
- }
-
- public function add($node, $weight = null) {
- $this->_nodes[] = $node;
- $this->_nodesCount++;
- }
-
- public function remove($node) {
- $this->_nodes = array_filter($this->_nodes, function($n) use($node) {
- return $n !== $node;
- });
- $this->_nodesCount = count($this->_nodes);
- }
-
- public function get($key) {
- $count = $this->_nodesCount;
- if ($count === 0) {
- throw new RuntimeException('No connections');
- }
- return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
- }
-
- public function generateKey($value) {
- return crc32($value);
- }
- }
-
- //配置键分布策略
- $options = array(
- 'key_distribution' => new NaiveDistributionStrategy(),
- );
-
- $redis = new PredisClient($multiple_servers, $options);
-
- for ($i = 0; $i set("key:$i", str_pad($i, 4, '0', 0));
- $redis->get("key:$i");
- }
-
- $server1 = $redis->getClientFor('first')->info();
- $server2 = $redis->getClientFor('second')->info();
-
- printf("Server '%s' has %d keys while server '%s' has %d keys.n",
- 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
- );
复制代码
|