Home > Article > Backend Development > Basic use cases of redis in PHP, redisPHP use cases_PHP tutorial
Download http://www.oschina.net/p/redis
After decompression, there are: lib source files, examples, test tests
Copy the lib directory to your project and you can start your predis operation.
//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 operations
$redis->set('library', 'predis');
$retval = $redis->get('library');
echo $retval; //Show 'predis'
//setex set a storage validity period
$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 existing values
$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 delete
$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, the entered 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, indicating replacement from the second character, then 'str' is 'abcd'
//substr partial acquisition operation
$redis->substr('str',0,2);//Indicates that starting from the 0th character, get the 2nd character, a total of 3 characters, return ' abc'
//strlen gets the string length
$redis->strlen(‘str’); //returns 4
//setbit/getbit bit storage and retrieval
$redis->setbit('binary',31,1); //Indicates that 1 is stored in the 31st bit, there may be big and small endian issues here ?But it doesn’t matter, there should be no problem with getbit
$redis->getbit('binary',31); //Return 1
//keys fuzzy search function, supports * and ? (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(); //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′); //Rename the original name The key for 'str' was changed 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 operations
*/
//rpush/rpushx Ordered list operation, insert elements from the back of the queue
//The difference between lpush/lpushx and rpush/rpushx is that it is inserted into the head of the queue, the same as above, the meaning of 'x' is only for already Operate on existing keys
$redis->rpush('fooList', 'bar1′); //Return the length of a list 1
$redis->lpush('fooList', 'bar0′) ; //Returns the length of a list 2
$redis->rpushx('fooList', 'bar2′); //Returns 3, rpushx only adds to the existing queue, otherwise returns 0
/ /llen returns the current list length
$redis->llen('fooList');//3
//lrange returns a range of elements in the queue
$redis->lrange('fooList',0,1); //The returned array contains 2 elements from 0th to 1st
$redis->lrange('fooList',0,-1);//Return the 0th to the last one, which is equivalent to returning all elements. Note that negative numbers are often used in redis, the same below
//lindex returns the list element at the specified sequence position
$redis->lindex(‘fooList’,1); //returns ‘bar1′
//lset modifies the value at the specified position in the queue
$redis->lset(‘fooList’,1,’123′);//modifies the element at position 1 and returns true
//lrem deletes the specified number of characters from the left in the queue
$redis->lrem('fooList',1,'_'); //Deletes the specified number of characters from the left in the queue (use -1 from the right) 1 character '_' (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 Modify the queue, keep a few elements from the left, and 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 an element before or after the specified element in the middle of the queue
$redis->linsert('list2′, 'before','ab1','123'); //Indicated in the element' Insert '123' before ab1'
$redis->linsert('list2', 'after','ab1','456'); //Indicates that '456'
//blpop/brpop blocks and waits for a queue to be non-empty, then pops out the leftmost or rightmost element (this function can be said to be very useful outside of PHP)
//brpoplpush is also blocking And wait for the operation, 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, and 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 removes the specified element
$redis->srem(‘set1′,’cd’); //Delete the ‘cd’ element
//spop pops up the first element
$redis->spop(‘set1′);
//smove moves 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 number of elements in the current set table
$redis->scard(‘set2′);//2
//sismember determines 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 the intersection/union/complement of the elements in the two tables
$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 elements and sets the serial number, returns true, 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); //Returns the elements between positions 0 and 1 (two)
$redis->zrange('zset1′,0,-1);//Return the elements between position 0 and the first element from the last (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 the elements is opposite to zrange
//zrangebyscore/zrevrangebyscore returns the elements in 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 the 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 value 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 index values; 'limit'=>array(1, 2), Indicates that a maximum of 2 items can be returned, and 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 means that elements with values greater than 5 after union are ranked first, and elements greater than 0 are ranked first. After
$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 range
$redis->zcount('zset1′,3,5);//2
$redis->zcount('zset1′, '(3′,5)); //'(3' means that the index value is between 3-5 but does not include 3. Similarly, you can also use '(5' to mean that the upper limit is 5 but does not include 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 elements with indexes between 0-2 ('ab','cd '), returns 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 elements; zrevrank returns 1 (the last one)
//zremrangebyrank deletes elements in the specified range of positions in the table
$redis->zremrangebyrank('zset1′,0,10); //Deletes elements at positions 0-10 and returns the number of deleted elements 2
/**
Hash table operation
*/
//hset/hget access hash table data
$redis->hset('hash1′,'key1′,'v1′); //Set key to 'key1' and value to 'v1' The elements are stored in the 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 deletes the element with the specified key in the hash table
$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 accesses multiple elements into 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 returns all keys in the hash table
$redis->hkeys('hash1′); //returns array('key1′,'key2′,'key3′,'key4′,' key5′)
//hvals returns all values in the hash table
$redis->hvals('hash1′); //returns 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' can be used in combination => 'desc','limit' => array(1, 2))
$redis->sort('tab',array('sort' => 'desc')); // Arrange in descending order, return array(17,3,2)
$redis->sort('tab',array('limit' => array(1, 2))); //Return 1 in the sequence position There are 2 elements (2 here refers to the number, not the position), return array(3,17)
$redis->sort('tab',array('limit' => array(' alpha' => true))); //Return array(17,2,3) sorted by the first character. Because the first character of 17 is '1', the first position is
$redis->sort(' tab',array('limit' => array('store' => 'ordered'))); //Indicates permanent sorting and returns the number of elements
$redis->sort('tab' ,array('limit' => array('get' => 'pre_*'))); //The wildcard character '*' is used to filter elements, which means that only elements starting with 'pre_' are returned
/**
redis management operations
*/
//select specifies the database to be operated
$redis->select(‘mydb’); //Specify mydb, create it if it does not exist
//flushdb Clear the current library
$redis->flushdb();
//move moves the elements of the current library to other libraries
$redis->set('foo', 'bar');
$redis->move('foo', 'mydb2' ); //If 'mydb2' library exists
//info displays service status information
$redis->info();
//slaveof Configure the slave server
$redis->slaveof('127.0.0.1′,80); //Configure the server of 127.0.0.1 port 80 as the slave server
$redis->slaveof (); //Clear slave 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 value corresponding to multiple keys
$ retval = $redis->mget(array_keys($mkv)); //Get the 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, transactional operation
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']
redis会将数据存储在内存中,断电丢失。这个要注意一下,如有必要就做个持久化。持久化的方法一言难尽,可以参考网上的文章。
php的redis扩展叫php-redis。网上有php-redis的中文手册,下面给你一个示例:
connect('127.0.0.1', 6379); // 6379是默认端口$result = $redis->set('9639002718',"comment"); // 设置键值echo $result = $redis->get('9639002718'); // 获取键值$all = $redis->getMultiple(array('9639002718', '9639002718')); // 同时获得多个键值// 没有提供获得所有键值的方法。下面这句我不确定是否能用,你可以试一试。$all = $redis->getMultiple(array('*'));
望采纳,谢谢支持!
Through redis ping command