Table of Contents
Redis,redis入门指南
Home php教程 php手册 Redis,redis入门指南

Redis,redis入门指南

Jun 13, 2016 am 08:53 AM
redis

Redis,redis入门指南

忙里偷闲啊...

<span>  1</span> <?<span>php
</span><span>  2</span> <span>/*</span><span>*
</span><span>  3</span> <span> * Description: Redis
</span><span>  4</span> <span> * Create date:2015-10-11 17:27
</span><span>  5</span> <span> * Author: zhaoyingnan
</span><span>  6</span> <span> *</span><span>*/</span>
<span>  7</span> 
<span>  8</span> <span>/*</span>
<span>  9</span> <span>__construct,__destruct,connect,pconnect,close,ping,echo,get,set,
</span><span> 10</span> <span>setex,psetex,setnx,getSet,randomKey,renameKey,renameNx,getMultiple,exists,delete,
</span><span> 11</span> <span>incr,incrBy,incrByFloat,decr,decrBy,type,append,getRange,setRange,getBit,
</span><span> 12</span> <span>setBit,strlen,getKeys,sort,sortAsc,sortAscAlpha,sortDesc,sortDescAlpha,lPush,rPush,
</span><span> 13</span> <span>lPushx,rPushx,lPop,rPop,blPop,brPop,lSize,lRemove,listTrim,lGet,
</span><span> 14</span> <span>lGetRange,lSet,lInsert,sAdd,sSize,sRemove,sMove,sPop,sRandMember,sContains,
</span><span> 15</span> <span>sMembers,sInter,sInterStore,sUnion,sUnionStore,sDiff,sDiffStore,setTimeout,save,bgSave,
</span><span> 16</span> <span>lastSave,flushDB,flushAll,dbSize,auth,ttl,pttl,persist,info,resetStat,
</span><span> 17</span> <span>select,move,bgrewriteaof,slaveof,object,bitop,bitcount,bitpos,mset,msetnx,
</span><span> 18</span> <span>rpoplpush,brpoplpush,zAdd,zDelete,zRange,zReverseRange,zRangeByScore,zRevRangeByScore,zCount,zDeleteRangeByScore,
</span><span> 19</span> <span>zDeleteRangeByRank,zCard,zScore,zRank,zRevRank,zInter,zUnion,zIncrBy,expireAt,pexpire,
</span><span> 20</span> <span>pexpireAt,hGet,hSet,hSetNx,hDel,hLen,hKeys,hVals,hGetAll,hExists,
</span><span> 21</span> <span>hIncrBy,hIncrByFloat,hMset,hMget,multi,discard,exec,pipeline,watch,unwatch,
</span><span> 22</span> <span>publish,subscribe,psubscribe,unsubscribe,punsubscribe,time,eval,evalsha,script,dump,
</span><span> 23</span> <span>restore,migrate,getLastError,clearLastError,_prefix,_serialize,_unserialize,client,scan,hscan,
</span><span> 24</span> <span>zscan,sscan,getOption,setOption,config,slowlog,getHost,getPort,getDBNum,getTimeout,
</span><span> 25</span> <span>getReadTimeout,getPersistentID,getAuth,isConnected,wait,pubsub,open,popen,lLen,sGetMembers,
</span><span> 26</span> <span>mget,expire,zunionstore,zinterstore,zRemove,zRem,zRemoveRangeByScore,zRemRangeByScore,zRemRangeByRank,zSize,
</span><span> 27</span> <span>substr,rename,del,keys,lrem,ltrim,lindex,lrange,scard,srem,
</span><span> 28</span> <span>sismember,zrevrange,sendEcho,evaluate,evaluateSha,
</span><span> 29</span>  <span>*/</span>
<span> 30</span> <span>//</span><span>PHP 中 Redis 的可操作的方法</span>
<span> 31</span> <span>$ReRedis</span>    =    <span>new</span> ReflectionClass('Redis'<span>);
</span><span> 32</span> <span>$arMethods</span>    =    <span>$ReRedis</span>-><span>getMethods();
</span><span> 33</span> <span>$arMethods</span>    =    objarray_to_array(<span>$arMethods</span><span>);
</span><span> 34</span> <span>//</span><span>print_r($arMethods);</span>
<span> 35</span> <span>function</span> objarray_to_array(<span>$obj</span><span>) {  
</span><span> 36</span>     <span>$ret</span> = <span>array</span><span>();  
</span><span> 37</span>     <span>foreach</span> (<span>$obj</span> <span>as</span> <span>$key</span> => <span>$value</span><span>) {  
</span><span> 38</span>         <span>if</span> (<span>gettype</span>(<span>$value</span>) == "array" || <span>gettype</span>(<span>$value</span>) == "object"<span>){  
</span><span> 39</span>             <span>$ret</span>[<span>$key</span>] =  objarray_to_array(<span>$value</span><span>);  
</span><span> 40</span>         }<span>else</span><span>{  
</span><span> 41</span>             <span>$ret</span>[<span>$key</span>] = <span>$value</span><span>;  
</span><span> 42</span> <span>        }  
</span><span> 43</span> <span>    }  
</span><span> 44</span>     <span>return</span> <span>$ret</span><span>;  
</span><span> 45</span> <span>}
</span><span> 46</span> <span>$i</span>    =    1<span>;
</span><span> 47</span> <span>foreach</span>(<span>$arMethods</span> <span>as</span> <span>$arVal</span><span>)
</span><span> 48</span>     <span>echo</span> <span>$arVal</span>['name'],','<span>;
</span><span> 49</span> 
<span> 50</span> <span>/*</span><span>***************************** Redis 介绍 ***********************************</span><span>*/</span>
<span> 51</span> <span>//</span><span>Redis,一款 内存高速缓存数据库,数据模型为 key-value
</span><span> 52</span> <span>//Redis 可持久化,(即它会将数据保存自硬盘中)保证了数据的安全
</span><span> 53</span> <span>//Redis 丰富的数据类型:string,list,hash,set,sorted set</span>
<span> 54</span> 
<span> 55</span> 
<span> 56</span> <span>/*</span><span>***************************** Redis 和 Memcached比较 ***********************</span><span>*/</span>
<span> 57</span> <span>//</span><span>    Redis 不仅仅支持简单的 key-value ,同时还提供list,set,hash等数据结构的存储
</span><span> 58</span> <span>//    Redis 支持 master-slave(主-从)模式应用
</span><span> 59</span> <span>//    Redis 支持数据的持久化,可以将内存中的数据村春在硬盘中,重启、断电的时候并不会丢失数据
</span><span> 60</span> <span>//    Redis 单个 value 的最大限制的 1GB,Memcached 只能保存 1MB</span>
<span> 61</span> 
<span> 62</span> 
<span> 63</span> <span>/*</span><span>***************************** Redis 中对 key 的操作 ************************</span><span>*/</span>
<span> 64</span> <span>/*</span><span>*
</span><span> 65</span> <span> * eixists key                    测试指定的 key 是否存在
</span><span> 66</span> <span> * del key1 key2 key3 ...        删除给定的 key
</span><span> 67</span> <span> * type    key                        返回给定的 key 的 value 类型
</span><span> 68</span> <span> * keys pattern                    返回匹配指定模式的所有的 key
</span><span> 69</span> <span> * rename oldkeyname newkeyname    改名字
</span><span> 70</span> <span> * dbsize                        返回当前数据库的 key 的数量
</span><span> 71</span> <span> * expire key seconds            为 key 设置过期时间
</span><span> 72</span> <span> * ttl key                        返回 key 的剩余过期时间
</span><span> 73</span> <span> * select db-index                选择数据库(0-15)
</span><span> 74</span> <span> * move key db-index            将 key 从当前数据库移动到指定的数据库
</span><span> 75</span> <span> * flushdb                        删除当前数据库中的所有的 key
</span><span> 76</span> <span> * flushall                        删除所有数据库中所有 key
</span><span> 77</span> <span> *</span><span>*/</span>
<span> 78</span> 
<span> 79</span> 
<span> 80</span> <span>/*</span><span>***************************** Redis 中对 string 类型的操作 *******************</span><span>*/</span>
<span> 81</span> <span>/*</span><span>*
</span><span> 82</span> <span> * set key value                设置 key 对应的值为 string 类型的  value
</span><span> 83</span> <span> * mset key1 value1 key2 value2 keyN valueN    一次性设置多个 key 的值
</span><span> 84</span> <span> * mget    key1 key2 keyN            一次性获取多个 key 的值
</span><span> 85</span> <span> * incr key                        对 key 的值进行自增操作,步进值为1,并返回新的值
</span><span> 86</span> <span> * decr key                        对 key 的值进行自减操作,步进值为1,并返回新的值
</span><span> 87</span> <span> * incrby key integer            同 incr ,但是步进值为指定的 integer ,并返回新的值
</span><span> 88</span> <span> * decrby key integer            同 decr ,但是步进值为指定的 integer ,并返回新的值
</span><span> 89</span> <span> * append key value                给指定的 key 对应的值追加 value
</span><span> 90</span> <span> * substr key start end            返回截取过的 key 对应的值,包括开始和结束的位置,下标从0开始
</span><span> 91</span> <span> *</span><span>*/</span>
<span> 92</span> 
<span> 93</span> 
<span> 94</span> <span>/*</span><span>***************************** Redis 中对 list 类型的操作 **********************</span><span>*/</span>
<span> 95</span> <span>//</span><span>list 类型是一个双向链表,通过 push,pop 操作从链表的头部或者尾部添加或删除元素。
</span><span> 96</span> <span>//应用的场景:获得最新登录的10个用户的信息</span>
<span> 97</span> <span>/*</span><span>*
</span><span> 98</span> <span> * lpush key value                在 key 对应的 list 的头部添加 value 元素,返回 list 中元素的个数
</span><span> 99</span> <span> * rpush key value                在 key 对应的 list 的尾部添加 value 元素,返回 list 中元素的个数
</span><span>100</span> <span> * rpop key                        在 key 对应的 list 的尾部删除一个元素,并返回该元素的内容
</span><span>101</span> <span> * lpop key                        在 key 对应的 list 的头部删除一个元素,并返回该元素的内容
</span><span>102</span> <span> * llen key                        返回 key 对应的 list 的中元素的个数,若不存在则为0,若不是 list 类型则报错
</span><span>103</span> <span> * lrange key start end            返回 key 对应的 list 的中指定区间内的元素,包括开始和结束的位置,下标从0开始
</span><span>104</span> <span> * ltrim key start key            截取 list,保留指定区间内的元素
</span><span>105</span> <span> *</span><span>*/</span>
<span>106</span> 
<span>107</span> 
<span>108</span> <span>/*</span><span>***************************** Redis 中对 set 类型的操作 ************************</span><span>*/</span>
<span>109</span> <span>//</span><span>set 无序集合,每个集合的元素是不会重复的,最多可以包含2的32次方个元素(交集、并集、差集)
</span><span>110</span> <span>//应用场景:QQ好友推荐,你和张三的共同好友</span>
<span>111</span> <span>/*</span><span>*
</span><span>112</span> <span> * sadd key member                添加一个 member 元素到 key 对应的 set 集合中,成功返回1,若元素已经存在,返回0
</span><span>113</span> <span> * sren key member1 memberN        从 key 对应的 set 集合中删除给定的元素,成功返回1
</span><span>114</span> <span> * scard key                    返回 key 对应的 set 集合中的元素个数
</span><span>115</span> <span> * smembers key                    返回 key 对应的 set 集合中的所有元素,是无序的
</span><span>116</span> <span> * sismember key member            判断 member 在 key 对应的 set 集合中是否存在,存在返回 1,否则为0
</span><span>117</span> <span> * smove key1 key2 member        将 key1 对应的 set 集合中的 member 移动到 key2 对应的 set 集合中
</span><span>118</span> <span> * sinter key1 key2 keyN        返回所有给定 key 对应的 set 集合的交集
</span><span>119</span> <span> * sunion key1 key2 keyN        返回所有给定 key 对应的 set 集合的并集
</span><span>120</span> <span> * sdiff key1 key2 keyN            返回所有给定 key 对应的 set 集合的差集
</span><span>121</span> <span> *</span><span>*/</span>
<span>122</span> 
<span>123</span> 
<span>124</span> <span>/*</span><span>***************************** Redis 中对 sorted set 类型的操作 ******************</span><span>*/</span>
<span>125</span> <span>//</span><span>sorted set 排序的集合,与 set 集合不同,它每个集合中的每个元素都是值、权重的组合
</span><span>126</span> <span>//应用场景:排行榜</span>
<span>127</span> <span>/*</span><span>*
</span><span>128</span> <span> * zadd key score member        添加元素到 key 对应的 set 集合,其中值为 member,权重为 score
</span><span>129</span> <span> * zrem key member                删除 key 对应的 set 集合中指定的元素 member
</span><span>130</span> <span> * zincrby key incr member        按照 incr 幅度增加 key 对应的 set 集合中 member 元素的 score 权重值
</span><span>131</span> <span> * zrank key member                返回指定元素 member 在 key 对应的 set 集合中的排名下标,排名按 score 小到大,下标0开
</span><span>132</span> <span> * zrevrank key member            返回指定元素 member 在 key 对应的 set 集合中的排名下标,排名按 score 大到小,下标0开
</span><span>133</span> <span> * zrange key start end            返回 key 对应的 set 集合中指定区间的元素的值,排序安 score 小到大,下标0开,含始末
</span><span>134</span> <span> * zrevrange key start end        返回 key 对应的 set 集合中指定区间的元素的值,排序安 score 大到小,下标0开,含始末
</span><span>135</span> <span> * zcard key                    返回 key 对应的 set 集合中的元素个数
</span><span>136</span> <span> * zscore key member            返回 key 对应的 set 集合中给定的值为 member 的元素的 score 的值
</span><span>137</span> <span> * zremrangebyrank key min max    删除 key 对应的 set 集合中排名在给定区间的元素(按 score 小到大排序)
</span><span>138</span> <span> *</span><span>*/</span>
<span>139</span> 
<span>140</span> 
<span>141</span> <span>/*</span><span>***************************** Redis 数据持久化 ***********************************</span><span>*/</span>
<span>142</span> <span>/*</span><span>*
</span><span>143</span> <span> * snap shotting 快照持久化
</span><span>144</span> <span> *        默认开启了该功能,一次性将 Redis 中的全部数据保存一份在硬盘中,数据非常多的话并不适合频繁地执行该操作
</span><span>145</span> <span> *        redis.conf
</span><span>146</span> <span> *            快照持久化的备份频率(数据修改的频率高/低,则备份频率也高/低)
</span><span>147</span> <span> *            save 900 1            #900 秒内如果超过 1 个 key 被修改,则发起一次快照保存
</span><span>148</span> <span> *            save 300 10            #300 秒内如果超过 10 个 key 被修改,则发起一次快照保存 
</span><span>149</span> <span> *            save 60 10000        #60 秒内如果超过 10000 个 key 被修改,则发起一次快照保存
</span><span>150</span> <span> *            dbfilename dump.rdb    #备份的文件名称
</span><span>151</span> <span> *            dir ./                #备份文件的保存路径
</span><span>152</span> <span> *        手动发起一次快照持久化
</span><span>153</span> <span> *            redis-cli -h 127.0.0.1 -p 6379 bgsave    #手动发起一次快照持久化
</span><span>154</span> <span> *</span><span>*/</span>
<span>155</span> 
<span>156</span> <span>/*</span><span>*
</span><span>157</span> <span> * append only file AOF持久化
</span><span>158</span> <span> *        本质:把用户执行的每个'写'指令都备份到文件中,还原数据的时候其实就是执行具体的指令
</span><span>159</span> <span> *        默认没有开启,开启的时候会将 Redis 内的数据清空,使用之前先开启
</span><span>160</span> <span> *        redis.conf
</span><span>161</span> <span> *            appendonly no        #默认不开启
</span><span>162</span> <span> *            appendfilename "appendonly.aof"    #备份文件的名称
</span><span>163</span> <span> *            dir ./              #备份文件的保存路径
</span><span>164</span> <span> *        开启 AOF 持久化时,应使用对应的配置文件重启 Redis
</span><span>165</span> <span> *            redis-server redis.conf
</span><span>166</span> <span> *        AOF 持久化的备份频率
</span><span>167</span> <span> *            redis.conf
</span><span>168</span> <span> *                # appendfsync always    #每次收到写指令就会立即备份,最安全,但最慢,开销大
</span><span>169</span> <span> *                appendfsync everysec    #每秒钟强制备份一次,在性能和持久化方面做了折中,默认
</span><span>170</span> <span> *                # appendfsync no        #完全依赖操作系统,性能最好,持久化没有保证,安全性最差
</span><span>171</span> <span> *        为 AOF 备份文件做优化压缩处理
</span><span>172</span> <span> *            例如将多个 incr 指令变为一个 set 指令
</span><span>173</span> <span> *                redis-cli -h 127.0.0.1 -p 6379 bgrewriteaof   #优化压缩
</span><span>174</span> <span> *</span><span>*/</span>
Copy after login

 

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)

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 clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

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 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 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 configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles