Home Backend Development PHP Tutorial Summary of usage of Redis function in php

Summary of usage of Redis function in php

Nov 02, 2017 am 09:30 AM
php redis Summarize

This article mainly introduces the usage of php Redis function, and summarizes and analyzes the php redis operation in the form of examples. Commonly used functions and specific usage methods are also attached with the php connection redis singleton class. Friends who need it can refer to it. The following

examples in this article summarize the usage of php Redis function. Share it with everyone for your reference, the details are as follows:

I have been using Redis with PHP, but it always feels unreliable, so I simply use this time to complete it in one go.
Almost all the Redis commands that can be operated in PHP I have typed it all over, including its return value. Even if I forget it next time, I can check it directly. Everyone can use it with confidence.

Tips:

The addition and modification operations of: string, set, sort set, hash are the same command, but when treating it as a modification operation, timely The successful return value is still 0

For the list structure, there is a set of methods for addition, deletion and modification.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

<?php

/*1.Connection*/

  $redis = new Redis();

  $redis->connect(&#39;127.0.0.1&#39;,6379,1);//短链接,本地host,端口为6379,超过1秒放弃链接

  $redis->open(&#39;127.0.0.1&#39;,6379,1);//短链接(同上)

  $redis->pconnect(&#39;127.0.0.1&#39;,6379,1);//长链接,本地host,端口为6379,超过1秒放弃链接

  $redis->popen(&#39;127.0.0.1&#39;,6379,1);//长链接(同上)

  $redis->auth(&#39;password&#39;);//登录验证密码,返回【true | false】

  $redis->select(0);//选择redis库,0~15 共16个库

  $redis->close();//释放资源

  $redis->ping(); //检查是否还再链接,[+pong]

  $redis->ttl(&#39;key&#39;);//查看失效时间[-1 | timestamps]

  $redis->persist(&#39;key&#39;);//移除失效时间[ 1 | 0]

  $redis->sort(&#39;key&#39;,[$array]);//返回或保存给定列表、集合、有序集合key中经过排序的元素,$array为参数limit等!【配合$array很强大】 [array|false]

/*2.共性的运算归类*/

  $redis->expire(&#39;key&#39;,10);//设置失效时间[true | false]

  $redis->move(&#39;key&#39;,15);//把当前库中的key移动到15库中[0|1]

//string

  $redis->strlen(&#39;key&#39;);//获取当前key的长度

  $redis->append(&#39;key&#39;,&#39;string&#39;);//把string追加到key现有的value中[追加后的个数]

  $redis->incr(&#39;key&#39;);//自增1,如不存在key,赋值为1(只对整数有效,存储以10进制64位,redis中为str)[new_num | false]

  $redis->incrby(&#39;key&#39;,$num);//自增$num,不存在为赋值,值需为整数[new_num | false]

  $redis->decr(&#39;key&#39;);//自减1,[new_num | false]

  $redis->decrby(&#39;key&#39;,$num);//自减$num,[ new_num | false]

  $redis->setex(&#39;key&#39;,10,&#39;value&#39;);//key=value,有效期为10秒[true]

//list

  $redis->llen(&#39;key&#39;);//返回列表key的长度,不存在key返回0, [ len | 0]

//set

  $redis->scard(&#39;key&#39;);//返回集合key的基数(集合中元素的数量)。[num | 0]

  $redis->sMove(&#39;key1&#39;, &#39;key2&#39;, &#39;member&#39;);//移动,将member元素从key1集合移动到key2集合。[1 | 0]

//Zset

  $redis->zcard(&#39;key&#39;);//返回集合key的基数(集合中元素的数量)。[num | 0]

  $redis->zcount(&#39;key&#39;,0,-1);//返回有序集key中,score值在min和max之间(默认包括score值等于min或max)的成员。[num | 0]

//hash

  $redis->hexists(&#39;key&#39;,&#39;field&#39;);//查看hash中是否存在field,[1 | 0]

  $redis->hincrby(&#39;key&#39;,&#39;field&#39;,$int_num);//为哈希表key中的域field的值加上量(+|-)num,[new_num | false]

  $redis->hlen(&#39;key&#39;);//返回哈希表key中域的数量。[ num | 0]

/*3.Server*/

  $redis->dbSize();//返回当前库中的key的个数

  $redis->flushAll();//清空整个redis[总true]

  $redis->flushDB();//清空当前redis库[总true]

  $redis->save();//同步??把数据存储到磁盘-dump.rdb[true]

  $redis->bgsave();//异步??把数据存储到磁盘-dump.rdb[true]

  $redis->info();//查询当前redis的状态 [verson:2.4.5....]

  $redis->lastSave();//上次存储时间key的时间[timestamp]

  $redis->watch(&#39;key&#39;,&#39;keyn&#39;);//监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断 [true]

  $redis->unwatch(&#39;key&#39;,&#39;keyn&#39;);//取消监视一个(或多个) key [true]

  $redis->multi(Redis::MULTI);//开启事务,事务块内的多条命令会按照先后顺序被放进一个队列当中,最后由 EXEC 命令在一个原子时间内执行。

  $redis->multi(Redis::PIPELINE);//开启管道,事务块内的多条命令会按照先后顺序被放进一个队列当中,最后由 EXEC 命令在一个原子时间内执行。

  $redis->exec();//执行所有事务块内的命令,;【事务块内所有命令的返回值,按命令执行的先后顺序排列,当操作被打断时,返回空值 false】

/*4.String,键值对,创建更新同操作*/

  $redis->setOption(Redis::OPT_PREFIX,&#39;hf_&#39;);//设置表前缀为hf_

  $redis->set(&#39;key&#39;,1);//设置key=aa value=1 [true]

  $redis->mset($arr);//设置一个或多个键值[true]

  $redis->setnx(&#39;key&#39;,&#39;value&#39;);//key=value,key存在返回false[|true]

  $redis->get(&#39;key&#39;);//获取key [value]

  $redis->mget($arr);//(string|arr),返回所查询键的值

  $redis->del($key_arr);//(string|arr)删除key,支持数组批量删除【返回删除个数】

  $redis->delete($key_str,$key2,$key3);//删除keys,[del_num]

  $redis->getset(&#39;old_key&#39;,&#39;new_value&#39;);//先获得key的值,然后重新赋值,[old_value | false]

/*5.List栈的结构,注意表头表尾,创建更新分开操作*/

  $redis->lpush(&#39;key&#39;,&#39;value&#39;);//增,只能将一个值value插入到列表key的表头,不存在就创建 [列表的长度 |false]

  $redis->rpush(&#39;key&#39;,&#39;value&#39;);//增,只能将一个值value插入到列表key的表尾 [列表的长度 |false]

  $redis->lInsert(&#39;key&#39;, Redis::AFTER, &#39;value&#39;, &#39;new_value&#39;);//增,将值value插入到列表key当中,位于值value之前或之后。[new_len | false]

  $redis->lpushx(&#39;key&#39;,&#39;value&#39;);//增,只能将一个值value插入到列表key的表头,不存在不创建 [列表的长度 |false]

  $redis->rpushx(&#39;key&#39;,&#39;value&#39;);//增,只能将一个值value插入到列表key的表尾,不存在不创建 [列表的长度 |false]

  $redis->lpop(&#39;key&#39;);//删,移除并返回列表key的头元素,[被删元素 | false]

  $redis->rpop(&#39;key&#39;);//删,移除并返回列表key的尾元素,[被删元素 | false]

  $redis->lrem(&#39;key&#39;,&#39;value&#39;,0);//删,根据参数count的值,移除列表中与参数value相等的元素count=(0|-n表头向尾|+n表尾向头移除n个value) [被移除的数量 | 0]

  $redis->ltrim(&#39;key&#39;,start,end);//删,列表修剪,保留(start,end)之间的值 [true|false]

  $redis->lset(&#39;key&#39;,index,&#39;new_v&#39;);//改,从表头数,将列表key下标为第index的元素的值为new_v, [true | false]

  $redis->lindex(&#39;key&#39;,index);//查,返回列表key中,下标为index的元素[value|false]

  $redis->lrange(&#39;key&#39;,0,-1);//查,(start,stop|0,-1)返回列表key中指定区间内的元素,区间以偏移量start和stop指定。[array|false]

/*6.Set,没有重复的member,创建更新同操作*/

  $redis->sadd(&#39;key&#39;,&#39;value1&#39;,&#39;value2&#39;,&#39;valuen&#39;);//增,改,将一个或多个member元素加入到集合key当中,已经存在于集合的member元素将被忽略。[insert_num]

  $redis->srem(&#39;key&#39;,&#39;value1&#39;,&#39;value2&#39;,&#39;valuen&#39;);//删,移除集合key中的一个或多个member元素,不存在的member元素会被忽略 [del_num | false]

  $redis->smembers(&#39;key&#39;);//查,返回集合key中的所有成员 [array | &#39;&#39;]

  $redis->sismember(&#39;key&#39;,&#39;member&#39;);//判断member元素是否是集合key的成员 [1 | 0]

  $redis->spop(&#39;key&#39;);//删,移除并返回集合中的一个随机元素 [member | false]

  $redis->srandmember(&#39;key&#39;);//查,返回集合中的一个随机元素 [member | false]

  $redis->sinter(&#39;key1&#39;,&#39;key2&#39;,&#39;keyn&#39;);//查,返回所有给定集合的交集 [array | false]

  $redis->sunion(&#39;key1&#39;,&#39;key2&#39;,&#39;keyn&#39;);//查,返回所有给定集合的并集 [array | false]

  $redis->sdiff(&#39;key1&#39;,&#39;key2&#39;,&#39;keyn&#39;);//查,返回所有给定集合的差集 [array | false]

/*7.Zset,没有重复的member,有排序顺序,创建更新同操作*/

  $redis->zAdd(&#39;key&#39;,$score1,$member1,$scoreN,$memberN);//增,改,将一个或多个member元素及其score值加入到有序集key当中。[num | 0]

  $redis->zrem(&#39;key&#39;,&#39;member1&#39;,&#39;membern&#39;);//删,移除有序集key中的一个或多个成员,不存在的成员将被忽略。[del_num | 0]

  $redis->zscore(&#39;key&#39;,&#39;member&#39;);//查,通过值反拿权 [num | null]

  $redis->zrange(&#39;key&#39;,$start,$stop);//查,通过(score从小到大)【排序名次范围】拿member值,返回有序集key中,【指定区间内】的成员 [array | null]

  $redis->zrevrange(&#39;key&#39;,$start,$stop);//查,通过(score从大到小)【排序名次范围】拿member值,返回有序集key中,【指定区间内】的成员 [array | null]

  $redis->zrangebyscore(&#39;key&#39;,$min,$max[,$config]);//查,通过scroe权范围拿member值,返回有序集key中,指定区间内的(从小到大排)成员[array | null]

  $redis->zrevrangebyscore(&#39;key&#39;,$max,$min[,$config]);//查,通过scroe权范围拿member值,返回有序集key中,指定区间内的(从大到小排)成员[array | null]

  $redis->zrank(&#39;key&#39;,&#39;member&#39;);//查,通过member值查(score从小到大)排名结果中的【member排序名次】[order | null]

  $redis->zrevrank(&#39;key&#39;,&#39;member&#39;);//查,通过member值查(score从大到小)排名结果中的【member排序名次】[order | null]

  $redis->ZINTERSTORE();//交集

  $redis->ZUNIONSTORE();//差集

/*8.Hash,表结构,创建更新同操作*/

  $redis->hset(&#39;key&#39;,&#39;field&#39;,&#39;value&#39;);//增,改,将哈希表key中的域field的值设为value,不存在创建,存在就覆盖【1 | 0】

  $redis->hget(&#39;key&#39;,&#39;field&#39;);//查,取值【value|false】

  $arr = array(&#39;one&#39;=>1,2,3);$arr2 = array(&#39;one&#39;,0,1);

  $redis->hmset(&#39;key&#39;,$arr);//增,改,设置多值$arr为(索引|关联)数组,$arr[key]=field, [ true ]

  $redis->hmget(&#39;key&#39;,$arr2);//查,获取指定下标的field,[$arr | false]

  $redis->hgetall(&#39;key&#39;);//查,返回哈希表key中的所有域和值。[当key不存在时,返回一个空表]

  $redis->hkeys(&#39;key&#39;);//查,返回哈希表key中的所有域。[当key不存在时,返回一个空表]

  $redis->hvals(&#39;key&#39;);//查,返回哈希表key中的所有值。[当key不存在时,返回一个空表]

  $redis->hdel(&#39;key&#39;,$arr2);//删,删除指定下标的field,不存在的域将被忽略,[num | false]

?>

Copy after login

Attachment: PHP connection redis database singleton class

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

<?php

class RedisConnect

{

  /**

   * Redis的ip

   *

   * @var string

   */

  const REDISHOSTNAME = "127.0.0.1";

  /**

   * Redis的port

   *

   * @var int

   */

  const REDISPORT = 6379;

  /**

   * Redis的超时时间

   *

   * @var int

   */

  const REDISTIMEOUT = 0;

  /**

   * Redis的password

   *

   * @var unknown_type

   */

  const REDISPASSWORD = "ehualu";

  /**

   * Redis的DBname

   *

   * @var int

   */

  const REDISDBNAME = 12;

  /**

   * 类单例

   *

   * @var object

   */

  private static $instance;

  /**

   * Redis的连接句柄

   *

   * @var object

   */

  private $redis;

  /**

   * 私有化构造函数,防止类外实例化

   *

   * @param unknown_type $dbnumber

   */

  private function construct ()

  {

    // 链接数据库

    $this->redis = new Redis();

    $this->redis->connect(self::REDISHOSTNAME, self::REDISPORT, self::REDISTIMEOUT);

    $this->redis->auth(self::REDISPASSWORD);

    $this->redis->select(self::REDISDBNAME);

  }

  /**

   * 私有化克隆函数,防止类外克隆对象

   */

  private function clone ()

  {}

  /**

   * 类的唯一公开静态方法,获取类单例的唯一入口

   *

   * @return object

   */

  public static function getRedisInstance ()

  {

    if (! (self::$instance instanceof self)) {

      self::$instance = new self();

    }

    return self::$instance;

  }

  /**

   * 获取redis的连接实例

   *

   * @return Redis

   */

  public function getRedisConn ()

  {

    return $this->redis;

  }

  /**

   * 需要在单例切换的时候做清理工作

   */

  public function destruct ()

  {

    self::$instance->redis->close();

    self::$instance = NULL;

  }

}

?>

Copy after login

The above is the detailed content of Summary of usage of Redis function in php. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles