Home Backend Development PHP Tutorial 30 php operation redis common method code examples

30 php operation redis common method code examples

Oct 14, 2019 pm 02:43 PM
redis

This article mainly introduces 30 code examples of common methods for operating redis in PHP. This article actually has more than 30 methods, which can operate string type, list type and set type data. Friends in need can refer to it

There are many redis operations. Here are some examples of PHP processing redis. I personally think some examples are commonly used. The following examples are all based on the php-redis extension.

1, connect

Description: The instance is connected to a Redis.

Parameters: host: string, port: int

Return value: BOOL Successful return: TRUE; Failure return: FALSE

Example:

connect('127.0.0.1', 6379); 
var_dump($result); //结果:bool(true) 
?>
Copy after login

2, set

Description: Set key and value Value

Parameter: Key Value

Return value: BOOL Success return: TRUE; Failure return: FALSE

Example:

connect('127.0.0.1', 6379); 
$result = $redis->set('test',"11111111111"); 
var_dump($result);    //结果:bool(true) 
?>
Copy after login

3, get

Description: Get the value for the specified key

Parameters: key

Return value: string or BOOL If the key does not exist, return FALSE. Otherwise, return the value corresponding to the specified key.

Example:

connect('127.0.0.1', 6379); 
$result = $redis->get('test'); 
var_dump($result);   //结果:string(11) "11111111111" 
?>
Copy after login

4,delete

Description: Delete the specified key

Parameters: a key, or undefined Number of parameters, array for each key: key1 key2 key3 ... keyN

Return value: Number of items deleted

Example:

connect('127.0.0.1', 6379); 
$redis->set('test',"1111111111111"); 
echo $redis->get('test');   //结果:1111111111111 
$redis->delete('test'); 
var_dump($redis->get('test'));  //结果:bool(false) 
?>
Copy after login

5,setnx

Description: If the key does not exist in the database, set the key value parameter

Parameter: key value

Return value: BOOL Successful return: TRUE; Failure return :FALSE

Example:

connect('127.0.0.1', 6379); 
$redis->set('test',"1111111111111"); 
$redis->setnx('test',"22222222"); 
echo $redis->get('test');  //结果:1111111111111 
$redis->delete('test'); 
$redis->setnx('test',"22222222"); 
echo $redis->get('test');  //结果:22222222 
?>
Copy after login

6, exists

Description: Verify whether the specified key exists

Parameter key

Return value: Bool Successful return: TRUE; Failure return: FALSE

Example:

connect('127.0.0.1', 6379); 
$redis->set('test',"1111111111111"); 
var_dump($redis->exists('test'));  //结果:bool(true) 
?>
Copy after login

7, incr

Description: Numeric increment storage key.

Parameters: key value: The value that will be added to the key

Return value: INT the new value

Instance:

connect('127.0.0.1', 6379); 
$redis->set('test',"123"); 
var_dump($redis->incr("test"));  //结果:int(124) 
var_dump($redis->incr("test"));  //结果:int(125) 
?>
Copy after login

8, decr

Description: The key value is stored numerically in descending order.

Parameters: key value: the value that will be added to the key

Return value: INT the new value

Instance:

connect('127.0.0.1', 6379); 
$redis->set('test',"123"); 
var_dump($redis->decr("test"));  //结果:int(122) 
var_dump($redis->decr("test"));  //结果:int(121) 
?>
Copy after login

9 , getMultiple

Description: Get the values ​​of all specified keys. If one or more keys do not exist, the value of that key in this array is false

Parameters: Array of lists containing the key values ​​

Return value: Returns an array containing the values ​​of all keys

Example:

connect('127.0.0.1', 6379); 
$redis->set('test1',"1"); 
$redis->set('test2',"2"); 
$result = $redis->getMultiple(array('test1','test2')); 
print_r($result);   //结果:Array ( [0] => 1 [1] => 2 ) 
?>
Copy after login

10, lpush

Description: Add a string value from the head of the list. Create the list if the key does not exist. If the key exists and is not a list, return FALSE.

Parameters: key, value

Return value: Return the array length on success, false on failure

Instance:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
var_dump($redis->lpush("test","111"));   //结果:int(1) 
var_dump($redis->lpush("test","222"));   //结果:int(2) 
?>
Copy after login

11, rpush

Description: Add a string value from the end of the list. Create the list if the key does not exist. If the key exists and is not a list, return FALSE.

Parameters: key, value

Return value: Return the array length on success, false on failure

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
var_dump($redis->lpush("test","111"));   //结果:int(1) 
var_dump($redis->lpush("test","222"));   //结果:int(2) 
var_dump($redis->rpush("test","333"));   //结果:int(3) 
var_dump($redis->rpush("test","444"));   //结果:int(4) 
?>
Copy after login

12, lpop

Description: Return and remove the first element of the list

Parameters: key

Return value: Return the first element successfully Value, returns false

on failure. Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush("test","111"); 
$redis->lpush("test","222"); 
$redis->rpush("test","333"); 
$redis->rpush("test","444"); 
var_dump($redis->lpop("test"));  //结果:string(3) "222" 
?>
Copy after login

13, lsize,llen

Description: The length of the returned list . If the list does not exist or is empty, the command returns 0. If the key is not a list, this command returns FALSE.

Parameters: Key

Return value: Return the array length on success, false on failure

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush("test","111"); 
$redis->lpush("test","222"); 
$redis->rpush("test","333"); 
$redis->rpush("test","444"); 
var_dump($redis->lsize("test"));  //结果:int(4) 
?>
Copy after login

14 , lget

Description: Returns the specified element stored in the list with the specified key. 0 first element, 1 second... -1 last element, -2 second last... Returns FALSE if the wrong index or key does not point to the list.

Parameter: key index

Return value: Return the value of the specified element if successful, false if failed

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush("test","111"); 
$redis->lpush("test","222"); 
$redis->rpush("test","333"); 
$redis->rpush("test","444"); 
var_dump($redis->lget("test",3));  //结果:string(3) "444" 
?>
Copy after login

15, lset

Description: Assign a new value to the index specified in the list. If the index does not exist, return false.

Parameter: key index value

Return value: true on success, false on failure

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush("test","111"); 
$redis->lpush("test","222"); 
var_dump($redis->lget("test",1));  //结果:string(3) "111" 
var_dump($redis->lset("test",1,"333"));  //结果:bool(true) 
var_dump($redis->lget("test",1));  //结果:string(3) "333" 
?>
Copy after login

16, lgetrange

Description:

Returns the specified element stored from the beginning to the end of the specified key list in the area, lGetRange(key, start, end). 0 the first element, 1 the second element... -1 the last element, -2 the penultimate element...

Parameters: key start end

Return value: Successfully returns the value found , failed false

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush("test","111"); 
$redis->lpush("test","222"); 
print_r($redis->lgetrange("test",0,-1));  //结果:Array ( [0] => 222 [1] => 111 ) 
?>
Copy after login

17,lremove

Description: Remove from the head of the list count matching values. If count is zero, all matching elements are removed. If count is negative, the content is deleted from the end.

Parameter: key count value

Return value: Return the number of deleted items if successful, false if failed

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->lpush('test','a'); 
$redis->lpush('test','b'); 
$redis->lpush('test','c'); 
$redis->rpush('test','a'); 
print_r($redis->lgetrange('test', 0, -1)); //结果:Array ( [0] => c [1] => b [2] => a [3] => a ) 
var_dump($redis->lremove('test','a',2));   //结果:int(2) 
print_r($redis->lgetrange('test', 0, -1)); //结果:Array ( [0] => c [1] => b ) 
?>
Copy after login

18, sadd

Description: Add a value to a Key. If this value is already in this Key, return FALSE.

Parameters: key value

Return value: true on success, false on failure

Example:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
var_dump($redis->sadd('test','111'));   //结果:bool(true) 
var_dump($redis->sadd('test','333'));   //结果:bool(true) 
print_r($redis->sort('test')); //结果:Array ( [0] => 111 [1] => 333 ) 
?>
Copy after login

19 ,sremove

描述:删除Key中指定的value值

参数:key member

返回值:true or false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd('test','111'); 
$redis->sadd('test','333'); 
$redis->sremove('test','111'); 
print_r($redis->sort('test'));    //结果:Array ( [0] => 333 ) 
?>
Copy after login

20,smove

描述:将Key1中的value移动到Key2中

参数:srcKey dstKey member

返回值:true or false

范例

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->delete('test1'); 
$redis->sadd('test','111'); 
$redis->sadd('test','333'); 
$redis->sadd('test1','222'); 
$redis->sadd('test1','444'); 
$redis->smove('test',"test1",'111'); 
print_r($redis->sort('test1'));    //结果:Array ( [0] => 111 [1] => 222 [2] => 444 ) 
?>
Copy after login

21,scontains

描述:检查集合中是否存在指定的值。

参数:key value

返回值:true or false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd('test','111'); 
$redis->sadd('test','112'); 
$redis->sadd('test','113'); 
var_dump($redis->scontains('test', '111')); //结果:bool(true) 
?>
Copy after login

22,ssize

描述:返回集合中存储值的数量

参数:key

返回值:成功返回数组个数,失败0

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd('test','111'); 
$redis->sadd('test','112'); 
echo $redis->ssize('test');   //结果:2 
?>
Copy after login

23,spop

描述:随机移除并返回key中的一个值

参数:key

返回值:成功返回删除的值,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
var_dump($redis->spop("test"));  //结果:string(3) "333" 
?>
Copy after login

24,sinter

描述:返回一个所有指定键的交集。如果只指定一个键,那么这个命令生成这个集合的成员。如果不存在某个键,则返回FALSE。

参数:key1, key2, keyN

返回值:成功返回数组交集,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
var_dump($redis->sinter("test","test1"));  //结果:array(1) { [0]=> string(3) "111" } 
?>
Copy after login

25,sinterstore

描述:执行sInter命令并把结果储存到新建的变量中。

参数:

Key: dstkey, the key to store the diff into.

Keys: key1, key2… keyN. key1..keyN are intersected as in sInter.

返回值:成功返回,交集的个数,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
var_dump($redis->sinterstore('new',"test","test1"));  //结果:int(1) 
var_dump($redis->smembers('new'));  //结果:array(1) { [0]=> string(3) "111" } 
?>
Copy after login

26,sunion

描述:

返回一个所有指定键的并集

参数:

Keys: key1, key2, … , keyN

返回值:成功返回合并后的集,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
print_r($redis->sunion("test","test1"));  //结果:Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 ) 
?>
Copy after login

27,sunionstore

描述:执行sunion命令并把结果储存到新建的变量中。

参数:

Key: dstkey, the key to store the diff into.

Keys: key1, key2… keyN. key1..keyN are intersected as in sInter.

返回值:成功返回,交集的个数,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
var_dump($redis->sinterstore('new',"test","test1"));  //结果:int(4) 
print_r($redis->smembers('new'));  //结果:Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 ) 
?>
Copy after login

28,sdiff

描述:返回第一个集合中存在并在其他所有集合中不存在的结果

参数:Keys: key1, key2, … , keyN: Any number of keys corresponding to sets in redis.

返回值:成功返回数组,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
print_r($redis->sdiff("test","test1"));  //结果:Array ( [0] => 222 [1] => 333 ) 
?>
Copy after login

29,sdiffstore

描述:执行sdiff命令并把结果储存到新建的变量中。

参数:

Key: dstkey, the key to store the diff into.

Keys: key1, key2, … , keyN: Any number of keys corresponding to sets in redis

返回值:成功返回数字,失败false

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
$redis->sadd("test","333"); 
$redis->sadd("test1","111"); 
$redis->sadd("test1","444"); 
var_dump($redis->sdiffstore('new',"test","test1"));  //结果:int(2) 
print_r($redis->smembers('new'));  //结果:Array ( [0] => 222 [1] => 333 ) 
?>
Copy after login

30,smembers, sgetmembers

描述:

返回集合的内容

参数:Key: key

返回值:An array of elements, the contents of the set.

范例:

connect('127.0.0.1', 6379); 
$redis->delete('test'); 
$redis->sadd("test","111"); 
$redis->sadd("test","222"); 
print_r($redis->smembers('test'));  //结果:Array ( [0] => 111 [1] => 222 ) 
?>
Copy after login

 php-redis当中,有很多不同名字,但是功能一样的函数,例如:lrem和lremove,这里就不例举了。

更多PHP相关知识,请访问PHP中文网

The above is the detailed content of 30 php operation redis common method code examples. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

See all articles