Basic use cases of redis in PHP, redisPHP use cases_PHP tutorial
Basic use cases of redis in PHP, redisPHP use cases
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

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment