Table des matières
PHPRedis的安装在这里:
键值操作
key
mset多个key操作
keys
getset key value
strlen
getrange(substr)
rename
renamex
append
incr
incrby
decr
decrby
setbit key offset value
getbit key offset
type
randomkey
object
move
Hash
hset key field value
hsetnx key field value
hmset key field value[field value…]
hget key field
hmget key field [field …]
hgetall key
hdel key field [field…]
hlen key
hexists key field
hincrby key field increment
hkeys key
hvals key
lpush key value[value…] 表头插入一个或多个值
lpushx key value
rpush key value
rpushx key value
lpop key
rpop key
blpop key [key…]
brpop key [key…]
llen key
lrange key start stop
lrem key count value
lset key index value
ltrim key start stop
lindex key index
linsert key
rpoplpush source destination
brpoplpush source destination timeout
集合(Set)
sadd key member [member …]
srem key member [member …]
smembers key
sismember key member
scard key
smove source destination member
spop key
srandmember
sinter key [key…]
sinterstore destination key[key…]
sunion key [key …]
sunionstore destination key[key…]
sdiff key[key…]
sdiffstore destination key[key…]
Sorted Set有序集
zadd key score member[[score member] [score member] …]
zrem key member [member…]
zcard key
zcount key min max
zscore key member
zincreby key increment member
zrange key start stop [WITHSCORES]
zrevrange key start stop [WITHSCORES]
zrangebyscore
zrevrangebyscore key max min [WITHSCORES] [LIMIT offset count]
zrank key member
zrevrank key member
ZREMRANGEBYRANK key start stop
ZREMRANGEBYSCORE key min max
ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]
ZUNIONSTORE
排序
sort 数值排序
alpha限定按字符排序
limit限定返回数量
SORT限定正序倒序
by外部排序
生命周期
ttl、expire、expireat
persit移除生存时间
数据库操作
选择数据库
清除
Maison développement back-end tutoriel php Redis 学习笔记5 常用php函数

Redis 学习笔记5 常用php函数

Jun 13, 2016 pm 12:22 PM
gt key redis

Redis 学习笔记五 常用php函数

PHPRedis的安装在这里:

http://blog.csdn.net/xundh/article/details/46288277

键值操作

<code class=" hljs lasso"><span class="hljs-variable">$redis</span> <span class="hljs-subst">=</span> <span class="hljs-literal">new</span> Redis();<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>connect(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">6379</span>);<span class="hljs-comment">//参数:connect(host,port,timeout)</span><span class="hljs-comment">//timeout可以为空,在redis.conf里timeout默认300</span><span class="hljs-comment">//pconnect不会主动关闭的连接</span></code>
Copier après la connexion

key

<code class=" hljs lasso"><span class="hljs-comment">//写入值</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span><span class="hljs-built_in">set</span>(<span class="hljs-variable">$work</span><span class="hljs-subst">-></span>uid, <span class="hljs-variable">$workString</span>);<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>setnx(<span class="hljs-variable">$work</span><span class="hljs-subst">-></span>uid,<span class="hljs-variable">$workString</span>); <span class="hljs-comment">//key不存在是赋值</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>setex(<span class="hljs-variable">$a</span>,<span class="hljs-number">50</span>,<span class="hljs-number">1</span>);                <span class="hljs-comment">//range设置值后ttl设为50</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>setrange(key,offset,value);<span class="hljs-comment">//获取值</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>get(<span class="hljs-variable">$work</span><span class="hljs-subst">-></span>uid);<span class="hljs-comment">//删除key</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>del(<span class="hljs-variable">$work</span><span class="hljs-subst">-></span>uid);var_dump(<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>get(<span class="hljs-variable">$work</span><span class="hljs-subst">-></span>uid));  <span class="hljs-comment">//返回bool(false)</span><span class="hljs-comment">//键是否存在</span><span class="hljs-keyword">if</span>(<span class="hljs-subst">!</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>exists(<span class="hljs-string">'key'</span>))   var_dump(<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>del(<span class="hljs-string">'key'</span>));       <span class="hljs-comment">//返回int(0)</span></code>
Copier après la connexion

mset多个key操作

<code class=" hljs php"><span class="hljs-comment">//设置mset</span><span class="hljs-variable">$array_mset</span>=[<span class="hljs-string">'a'</span>=><span class="hljs-number">1</span>,<span class="hljs-string">'b'</span>=><span class="hljs-number">2</span>];<span class="hljs-variable">$redis</span>->mset(<span class="hljs-variable">$array</span>);<span class="hljs-variable">$redis</span>->msetnx(<span class="hljs-variable">$array</span>);    <span class="hljs-comment">//key不存在时才写入,但一次要么全写,要么全不写。</span><span class="hljs-comment">//读取mset</span><span class="hljs-variable">$array_mget</span>=[<span class="hljs-string">'a'</span>,<span class="hljs-string">'b'</span>];<span class="hljs-variable">$redis</span>->mget(<span class="hljs-variable">$arram_mget</span>);<span class="hljs-comment">//删除多个key</span><span class="hljs-variable">$redis</span>->del(<span class="hljs-variable">$array_mget</span>);</code>
Copier après la connexion

keys

<code class=" hljs php"><span class="hljs-comment">//读取keys</span><span class="hljs-variable">$array_mset_keys</span>=[<span class="hljs-string">'abc'</span>=><span class="hljs-number">1</span>,<span class="hljs-string">'bcd'</span>=><span class="hljs-number">2</span>,<span class="hljs-string">'cde'</span>=><span class="hljs-number">3</span>];<span class="hljs-variable">$redis</span>->keys(<span class="hljs-string">'*a*'</span>);  <span class="hljs-comment">//返回['a'=>1];</span><span class="hljs-variable">$redis</span>->keys(<span class="hljs-string">'b??'</span>);  <span class="hljs-comment">//返回['b'=>2];</span><span class="hljs-variable">$redis</span>->keys(<span class="hljs-string">'*'</span>);    <span class="hljs-comment">//返回所有keys</span></code>
Copier après la connexion

getset key value

设置值并返回旧值

strlen

返回字符串长度

getrange(substr)

字符串截取

rename

键改名

<code class=" hljs ruby"><span class="hljs-variable">$redis</span>->rename(<span class="hljs-string">'a'</span>,<span class="hljs-string">'a1'</span>);    <span class="hljs-regexp">//</span>成功返回<span class="hljs-keyword">true</span>,键不存在时返回<span class="hljs-keyword">false</span>,newkey已经存在其值会被覆盖;</code>
Copier après la connexion

renamex

键改名,newkey存在时不改

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>renamex(<span class="hljs-string">'a'</span>,<span class="hljs-string">'a1'</span>); <span class="hljs-comment">//a1如果已经存在,返回0;</span></code>
Copier après la connexion

append

字符串追加

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>append(<span class="hljs-string">'a'</span>,<span class="hljs-string">'12345'</span>) ;<span class="hljs-comment">//如果a不存在,就是普通的set操作</span></code>
Copier après la connexion

incr

储存的数字值增1

incrby

值增increment

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>incrby(<span class="hljs-string">'a'</span>,<span class="hljs-number">10</span>);</code>
Copier après la connexion

decr

数字值减1

decrby

数字值减decrement

setbit key offset value

设置或清除指定位

getbit key offset

获取指定偏移量上的位

type

返回key值类型
返回值有以下几种:

none (key不存在) int(0)
string 字符串 int(1)
list 列表 int(3)
set 集合 int(2)
zset 有序集合 int(4)
hash 哈希表 int(5)

randomkey

随机返回一个key

<code class=" hljs bash"><span class="hljs-built_in">echo</span> <span class="hljs-variable">$redis</span>->randomkey();   //如果没有key 返回<span class="hljs-literal">false</span></code>
Copier après la connexion

object

查看对象

move

移动数据

<code class=" hljs ruby"><span class="hljs-variable">$redis</span>-><span class="hljs-constant">MOVE</span>(<span class="hljs-string">'a'</span>,<span class="hljs-number">1</span>));   <span class="hljs-regexp">//</span>把键a从当前数据库移到<span class="hljs-number">1</span>里。如果key不存在,返回<span class="hljs-keyword">false</span>; 目标数据库存在key时,返回<span class="hljs-keyword">false</span>.</code>
Copier après la connexion

Hash

hset key field value

设置哈希值

hsetnx key field value

不存在时设置值

hmset key field value[field value…]

设置多个哈希值

hget key field

获取hash域值

hmget key field [field …]

获取若干个域值

hgetall key

返回key所有域和值

hdel key field [field…]

删除一个或多个域

hlen key

返回key里域数量

hexists key field

查看key里给定域的field是否存在

hincrby key field increment

域值增加increment

hkeys key

返回所有域

hvals key

返回key所有值

lpush key value[value…] 表头插入一个或多个值

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>lpush(<span class="hljs-string">'a'</span>,<span class="hljs-number">1</span>);<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>lpush(<span class="hljs-string">'a'</span>,<span class="hljs-number">2</span>);</code>
Copier après la connexion

lpushx key value

当且仅当key存在并且是一个列表时才插入

rpush key value

表尾插入

rpushx key value

lpop key

移除并返回key头元素

rpop key

移除并返回key的尾元素

blpop key [key…]

timeout lpop的阻塞版本,如果没有可供弹出的元素,程序会等待。

brpop key [key…]

timeout rpop的阻塞版本

llen key

返回列表 key的长度

lrange key start stop

返回区间

lrem key count value

移除列表值为value的元素
count>0 从表头向表尾搜索,移除值为value的元素,数量为count
count<0 从表尾向表头,移除值为value的元素,数量为-count
count=0 移除值为value的元素

lset key index value

设置key下标为index的值

ltrim key start stop

对列表修剪,删除区间外元素

lindex key index

返回下标为index的元素

linsert key

插入

rpoplpush source destination

弹出最后一个元素,把元素插入到列表destination里作为表头

brpoplpush source destination timeout

阻塞

集合(Set)

sadd key member [member …]

插入元素到集合里

srem key member [member …]

移除元素

smembers key

返回集合成员

sismember key member

判断member是否是key的成员

scard key

返回集合key的基数

smove source destination member

member元素从source移动到destination

spop key

移除并返回集合中的一个随机元素

srandmember

返回集合中一个随机元素

sinter key [key…]

返回集合成员

sinterstore destination key[key…]

返回成员到destination里,如果目标存在则覆盖

sunion key [key …]

返回集合全部成员

sunionstore destination key[key…]

返回成员保存到destination

sdiff key[key…]

返回一个集合的全部成员

sdiffstore destination key[key…]

结果保存到destination

Sorted Set有序集

zadd key score member[[score member] [score member] …]

一个或多个member及其score加入到有序集key中

zrem key member [member…]

移除有序集key中的一个或多个成员

zcard key

返回有序集key的基数

zcount key min max

返回有序集key中,score值在min与max之间的成员

zscore key member

返回有序集key中成员member的score值

zincreby key increment member

给member成员的score值增量

zrange key start stop [WITHSCORES]

返回有序集key中指定区间成员,score从小到大

zrevrange key start stop [WITHSCORES]

返回key中指定区间内的成员,score从大到小

zrangebyscore

返回区间成员,score从小到大

zrevrangebyscore key max min [WITHSCORES] [LIMIT offset count]

返回敬意成员,score从大到小

zrank key member

返回member排名,score从小到大

zrevrank key member

member排名,score递减

ZREMRANGEBYRANK key start stop

移除成员,下标在start stop之间

ZREMRANGEBYSCORE key min max

移除成员,score在min与max之间

ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]

计算有序集交集

ZUNIONSTORE

计算有序集并集

排序

sort 数值排序

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>SORT(<span class="hljs-string">'a'</span>);   <span class="hljs-comment">//返回排序结果</span></code>
Copier après la connexion

alpha限定按字符排序

<code class=" hljs php"><span class="hljs-variable">$redis</span>->SORT(<span class="hljs-string">'a'</span>,<span class="hljs-keyword">array</span>(<span class="hljs-string">'ALPHA'</span>=><span class="hljs-keyword">TRUE</span>)); <span class="hljs-comment">//返回排序结果</span></code>
Copier après la connexion

limit限定返回数量

<code class=" hljs php"><span class="hljs-variable">$redis</span>->SORT(<span class="hljs-string">'a'</span>,<span class="hljs-keyword">array</span>(<span class="hljs-string">'LIMIT'</span>=><span class="hljs-keyword">array</span>(<span class="hljs-number">0</span>,<span class="hljs-number">5</span>));</code>
Copier après la connexion

SORT限定正序倒序

<code class=" hljs php"><span class="hljs-variable">$redis</span>->SORT(<span class="hljs-string">'a'</span>,<span class="hljs-keyword">array</span>(<span class="hljs-string">'SORT'</span>=><span class="hljs-string">'DESC'</span>));</code>
Copier après la connexion

by外部排序

<code class=" hljs php"><span class="hljs-variable">$redis</span>->SORT(<span class="hljs-string">'a'</span>,<span class="hljs-keyword">array</span>(<span class="hljs-string">'BY'</span>=><span class="hljs-string">''</span>));</code>
Copier après la connexion

排序其它用法较多,这里不再详细一一列举。

生命周期

ttl、expire、expireat

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span><span class="hljs-built_in">set</span>(<span class="hljs-string">'a'</span>,<span class="hljs-number">12345</span>);<span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>expire(<span class="hljs-string">'a'</span>,<span class="hljs-number">30</span>); <span class="hljs-comment">//单位秒</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>expireat(<span class="hljs-string">'a'</span>,<span class="hljs-string">'1435152916'</span>); <span class="hljs-comment">//接受时间戳</span>echo <span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>get(<span class="hljs-string">'a'</span>);  <span class="hljs-comment">//如果已经过期,返回false</span>echo <span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>ttl(<span class="hljs-string">'a'</span>);  <span class="hljs-comment">//返回剩余时间(秒)。如果未赋expire值,返回-1;如果键不存在,也返回-1</span></code>
Copier après la connexion

persit移除生存时间

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>persist(<span class="hljs-string">'a'</span>);</code>
Copier après la connexion

数据库操作

选择数据库

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span><span class="hljs-keyword">SELECT</span>(<span class="hljs-number">0</span>);    <span class="hljs-comment">//默认就是数据库0 </span></code>
Copier après la connexion

清除

<code class=" hljs lasso"><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>FLUSHALL(); <span class="hljs-comment">//删除所有数据库</span><span class="hljs-variable">$redis</span><span class="hljs-subst">-></span>flushdb();  <span class="hljs-comment">//删除当前数据库所有key</span></code>
Copier après la connexion
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment construire le mode Cluster Redis Comment construire le mode Cluster Redis Apr 10, 2025 pm 10:15 PM

Le mode Redis Cluster déploie les instances Redis sur plusieurs serveurs grâce à la rupture, à l'amélioration de l'évolutivité et de la disponibilité. Les étapes de construction sont les suivantes: Créez des instances de redis étranges avec différents ports; Créer 3 instances Sentinel, Moniteur Redis Instances et basculement; Configurer les fichiers de configuration Sentinel, ajouter des informations d'instance Redis de surveillance et des paramètres de basculement; Configurer les fichiers de configuration d'instance Redis, activer le mode de cluster et spécifier le chemin du fichier d'informations de cluster; Créer un fichier nœuds.conf, contenant des informations de chaque instance redis; Démarrez le cluster, exécutez la commande CREATE pour créer un cluster et spécifiez le nombre de répliques; Connectez-vous au cluster pour exécuter la commande d'informations de cluster pour vérifier l'état du cluster; faire

Comment effacer les données redis Comment effacer les données redis Apr 10, 2025 pm 10:06 PM

Comment effacer les données Redis: utilisez la commande flushall pour effacer toutes les valeurs de clé. Utilisez la commande flushdb pour effacer la valeur clé de la base de données actuellement sélectionnée. Utilisez SELECT pour commuter les bases de données, puis utilisez FlushDB pour effacer plusieurs bases de données. Utilisez la commande del pour supprimer une clé spécifique. Utilisez l'outil Redis-CLI pour effacer les données.

Comment lire la file d'attente redis Comment lire la file d'attente redis Apr 10, 2025 pm 10:12 PM

Pour lire une file d'attente à partir de Redis, vous devez obtenir le nom de la file d'attente, lire les éléments à l'aide de la commande LPOP et traiter la file d'attente vide. Les étapes spécifiques sont les suivantes: Obtenez le nom de la file d'attente: Nommez-le avec le préfixe de "Fitre:" tel que "Fitre: My-Quyue". Utilisez la commande LPOP: éjectez l'élément de la tête de la file d'attente et renvoyez sa valeur, telle que la file d'attente LPOP: My-Queue. Traitement des files d'attente vides: si la file d'attente est vide, LPOP renvoie NIL et vous pouvez vérifier si la file d'attente existe avant de lire l'élément.

Comment utiliser la commande redis Comment utiliser la commande redis Apr 10, 2025 pm 08:45 PM

L'utilisation de la directive Redis nécessite les étapes suivantes: Ouvrez le client Redis. Entrez la commande (Verbe Key Value). Fournit les paramètres requis (varie de l'instruction à l'instruction). Appuyez sur Entrée pour exécuter la commande. Redis renvoie une réponse indiquant le résultat de l'opération (généralement OK ou -err).

Comment utiliser Redis Lock Comment utiliser Redis Lock Apr 10, 2025 pm 08:39 PM

L'utilisation des opérations Redis pour verrouiller nécessite l'obtention du verrouillage via la commande setnx, puis en utilisant la commande Expire pour définir le temps d'expiration. Les étapes spécifiques sont les suivantes: (1) Utilisez la commande setnx pour essayer de définir une paire de valeurs de clé; (2) Utilisez la commande Expire pour définir le temps d'expiration du verrou; (3) Utilisez la commande del pour supprimer le verrouillage lorsque le verrouillage n'est plus nécessaire.

Comment lire le code source de Redis Comment lire le code source de Redis Apr 10, 2025 pm 08:27 PM

La meilleure façon de comprendre le code source redis est d'aller étape par étape: familiarisez-vous avec les bases de Redis. Sélectionnez un module ou une fonction spécifique comme point de départ. Commencez par le point d'entrée du module ou de la fonction et affichez le code ligne par ligne. Affichez le code via la chaîne d'appel de fonction. Familiez les structures de données sous-jacentes utilisées par Redis. Identifiez l'algorithme utilisé par Redis.

Comment utiliser la ligne de commande redis Comment utiliser la ligne de commande redis Apr 10, 2025 pm 10:18 PM

Utilisez l'outil de ligne de commande redis (Redis-CLI) pour gérer et utiliser Redis via les étapes suivantes: Connectez-vous au serveur, spécifiez l'adresse et le port. Envoyez des commandes au serveur à l'aide du nom et des paramètres de commande. Utilisez la commande d'aide pour afficher les informations d'aide pour une commande spécifique. Utilisez la commande QUIT pour quitter l'outil de ligne de commande.

Comment configurer le temps d'exécution du script LUA dans Centos Redis Comment configurer le temps d'exécution du script LUA dans Centos Redis Apr 14, 2025 pm 02:12 PM

Sur CentOS Systems, vous pouvez limiter le temps d'exécution des scripts LUA en modifiant les fichiers de configuration Redis ou en utilisant des commandes Redis pour empêcher les scripts malveillants de consommer trop de ressources. Méthode 1: Modifiez le fichier de configuration Redis et localisez le fichier de configuration Redis: le fichier de configuration redis est généralement situé dans /etc/redis/redis.conf. Edit Fichier de configuration: Ouvrez le fichier de configuration à l'aide d'un éditeur de texte (tel que VI ou NANO): Sudovi / etc / redis / redis.conf Définissez le délai d'exécution du script LUA: Ajouter ou modifier les lignes suivantes dans le fichier de configuration pour définir le temps d'exécution maximal du script LUA (unité: millisecondes)

See all articles