Home > Backend Development > PHP Tutorial > PHP operation Redis detailed case

PHP operation Redis detailed case

迷茫
Release: 2023-03-05 10:08:02
Original
1548 people have browsed it

$redis = new Redis();

connect, open link redis service

Parameters

host: string, service address

port: int, port number

timeout: float, link duration (optional, The default is 0, no limit to the link time)

Note: There is also time in redis.conf, the default is 300

pconnect, popen will not actively close the link

Reference Above

setOption sets the redis mode

getOption checks the mode set by redis

ping checks the connection status

get gets the value of a certain key (string value)

If the key does not exist, return false

set writes the key and value (string value)

If the writing is successful, return ture

setex Write value with survival time

$redis->setex('key', 3600, 'value'); // sets key → value, with 1h TTL.
Copy after login

setnx Determine whether it is repeated, write value

$redis->setnx('key', 'value');
$redis->setnx('key', 'value');
Copy after login

delete Delete the value of the specified key

Return the number of deleted keys ( Long integer)

$redis->delete('key1', 'key2');
$redis->delete(array('key3', 'key4', 'key5'));
Copy after login

Get the survival time of a key

persist

Remove the key whose survival time expires

If the key expires true if not Expires false

mset (redis version 1.1 or above can only be used)

Assign values ​​to multiple keys at the same time

$redis->mset(array('key0' => 'value0', 'key1' => 'value1'));
Copy after login

multi, exec, discard

Enter Or exit transaction mode

The parameter can be Redis::MULTI or Redis::PIPELINE. The default is Redis::MULTI

Redis::MULTI: execute multiple operations as one transaction

Redis::PIPELINE: Allows (multiple) execution commands to be sent to the server simply and faster, but without any atomicity guarantee

discard: delete a transaction

Return value

multi(), returns a redis object and enters multi-mode mode. Once it enters multi-mode mode, all methods called in the future will return the same object until the exec() method is called. .

watch, unwatch (after testing the code, the effect mentioned cannot be achieved)

Monitor whether the value of a key is changed by other programs. If this key is modified between watch and exec (method), the execution of this MULTI/EXEC transaction will fail (return false)

unwatch cancels all key

parameters monitored by this program, A list of a pair of keys

$redis->watch('x');
$ret = $redis->multi() ->incr('x') ->exec();
subscribe *
Copy after login

Method callback. Note that this method may change in the future

publish *

Publish content to a certain channel. Note that this method may change in the future

exists

Determine whether the key exists. If there is true but not false

incr, the value in incrBy

key will be incremented by 1. If the second parameter is filled in, it will be incremented by the value filled in the second parameter

$redis->incr('key1');
$redis->incrBy('key1', 10);
Copy after login

decr, decrBy

Do subtraction, the usage method is the same as incr

getMultiple

Pass parameters

Array composed of keys

Return parameters

If the key exists, return value, if it does not exist, return false

$redis->set('key1', 'value1'); $redis->set('key2', 'value2'); $redis->set('key3', 'value3'); $redis->getMultiple(array('key1', 'key2', 'key3'));
$redis->lRem('key1', 'A', 2);
$redis->lRange('key1', 0, -1);
Copy after login

list related operations

lPush

$redis->lPush(key, value);
Copy after login

Add an element with a value of value to the left (head) of the list named key

rPush

$redis->rPush(key, value);
Copy after login

Add an element with a value of value to the right (tail) of the list named key

lPushx/rPushx

$redis->lPushx(key, value);
Copy after login

Add an element with value to the left (head)/right (tail) of the list named key. If value already exists, it will not be added

lPop/rPop

$redis->lPop('key');
Copy after login

Output the first element from the left (head)/right (tail) of the list named key, delete the element

blPop/brPop

$redis->blPop('key1', 'key2', 10);
Copy after login

The block version of the lpop command. That is, when timeout is 0, if the list named key i does not exist or the list is empty, the command ends. If timeout>0, when encountering the above situation, wait for timeout seconds. If the problem is not solved, perform pop operation on the list starting from keyi+1

lSize

$redis->lSize('key');
Copy after login

The return name is key How many elements does the list have?

lIndex, lGet

$redis->lGet('key', 0);
Copy after login

Returns the element at the index position in the list named key

lSet

$redis->lSet('key', 0, 'X');
Copy after login

to the name named The element at the index position in the key's list is assigned value

lRange, lGetRange

$redis->lRange('key1', 0, -1);
Copy after login

returns the elements between start and end in the list named key (end is -1, return all)

lTrim, listTrim

$redis->lTrim('key', start, end);
Copy after login

Intercept the list named key and keep the elements between start and end

lRem, lRemove

$redis->lRem('key', 'A', 2);
Copy after login

Delete count The element whose value is value in the list named key. count is 0, delete all elements with value, count>0 deletes count elements with value from beginning to end, count<0 deletes |count| elements with value from end to end

lInsert

In the list named key, find the value of pivot, and determine whether newvalue is placed before or after pivot according to the parameters Redis::BEFORE | Redis::AFTER. If the key does not exist, it will not be inserted. If the pivot does not exist, return -1

$redis->delete('key1'); $redis->lInsert('key1', Redis::AFTER, 'A', 'X'); $redis->lPush('key1', 'A'); $redis->lPush('key1', 'B'); $redis->lPush('key1', 'C'); $redis->lInsert('key1', Redis::BEFORE, 'C', 'X');
$redis->lRange(&#39;key1&#39;, 0, -1);
$redis->lInsert('key1', Redis::AFTER, 'C', 'Y');
$redis->lRange(&#39;key1&#39;, 0, -1);
$redis->lInsert('key1', Redis::AFTER, 'W', 'value');
Copy after login

rpoplpush

Return and delete the tail element of the list named srckey, and add the element to the name For the head of the list of dstkey

$redis->delete(&#39;x&#39;, &#39;y&#39;);
$redis->lPush(&#39;x&#39;, &#39;abc&#39;); $redis->lPush(&#39;x&#39;, &#39;def&#39;); $redis->lPush(&#39;y&#39;, &#39;123&#39;); $redis->lPush(&#39;y&#39;, &#39;456&#39;); // move the last of x to the front of y. var_dump($redis->rpoplpush(&#39;x&#39;, &#39;y&#39;));
var_dump($redis->lRange(&#39;x&#39;, 0, -1));
var_dump($redis->lRange(&#39;y&#39;, 0, -1));
string(3) "abc"
array(1) { [0]=> string(3) "def" }
array(3) { [0]=> string(3) "abc" [1]=> string(3) "456" [2]=> string(3) "123" }
Copy after login

SET operation related

sAdd

Add the element value to the set named key. If the value exists, do not write it, return false

$redis->sAdd(key , value);
Copy after login

sRem, sRemove

Delete the element value in the set named key

$redis->sAdd(&#39;key1&#39; , &#39;set1&#39;);
$redis->sAdd(&#39;key1&#39; , &#39;set2&#39;);
$redis->sAdd(&#39;key1&#39; , &#39;set3&#39;);
$redis->sRem(&#39;key1&#39;, &#39;set2&#39;);
Copy after login

sMove

Remove the value element from the set named srckey Move to the collection named dstkey

$redis->sMove(seckey, dstkey, value);
Copy after login

sIsMember, sContains

Check whether there is a value element in the collection named key, if there is true but not false

$redis->sIsMember(key, value);
Copy after login

sCard, sSize

返回名称为key的set的元素个数

sPop

随机返回并删除名称为key的set中一个元素

sRandMember

随机返回名称为key的set中一个元素,不删除

sInter

求交集

sInterStore

求交集并将交集保存到output的集合

$redis->sInterStore(&#39;output&#39;, &#39;key1&#39;, &#39;key2&#39;, &#39;key3&#39;)
Copy after login

sUnion

求并集

$redis->sUnion(&#39;s0&#39;, &#39;s1&#39;, &#39;s2&#39;);
Copy after login

s0,s1,s2 同时求并集

sUnionStore

求并集并将并集保存到output的集合

$redis->sUnionStore(&#39;output&#39;, &#39;key1&#39;, &#39;key2&#39;, &#39;key3&#39;);
Copy after login

sDiff

求差集

sDiffStore

求差集并将差集保存到output的集合

sMembers, sGetMembers

返回名称为key的set的所有元素

sort

排序,分页等

参数

&#39;by&#39; => &#39;some_pattern_*&#39;,
&#39;limit&#39; => array(0, 1),
&#39;get&#39; => &#39;some_other_pattern_*&#39; or an array of patterns,
&#39;sort&#39; => &#39;asc&#39; or &#39;desc&#39;,
&#39;alpha&#39; => TRUE,
&#39;store&#39; => &#39;external-key&#39;
Copy after login

例子

$redis->delete(&#39;s&#39;); $redis->sadd(&#39;s&#39;, 5); $redis->sadd(&#39;s&#39;, 4); $redis->sadd(&#39;s&#39;, 2); $redis->sadd(&#39;s&#39;, 1); $redis->sadd(&#39;s&#39;, 3);
var_dump($redis->sort(&#39;s&#39;)); // 1,2,3,4,5
var_dump($redis->sort(&#39;s&#39;, array(&#39;sort&#39; => &#39;desc&#39;))); // 5,4,3,2,1
var_dump($redis->sort(&#39;s&#39;, array(&#39;sort&#39; => &#39;desc&#39;, &#39;store&#39; => &#39;out&#39;))); // (int)5
Copy after login

string命令

getSet

返回原来key中的值,并将value写入key

$redis->set(&#39;x&#39;, &#39;42&#39;);
$exValue = $redis->getSet(&#39;x&#39;, &#39;lol&#39;); // return &#39;42&#39;, replaces x by &#39;lol&#39;
$newValue = $redis->get(&#39;x&#39;)&#39; // return &#39;lol&#39;
Copy after login

append

string,名称为key的string的值在后面加上value

$redis->set(&#39;key&#39;, &#39;value1&#39;);
$redis->append(&#39;key&#39;, &#39;value2&#39;);
$redis->get(&#39;key&#39;);
Copy after login

getRange (方法不存在)

返回名称为key的string中start至end之间的字符

$redis->set(&#39;key&#39;, &#39;string value&#39;);
$redis->getRange(&#39;key&#39;, 0, 5);
$redis->getRange(&#39;key&#39;, -5, -1);
Copy after login

setRange (方法不存在)

改变key的string中start至end之间的字符为value

$redis->set(&#39;key&#39;, &#39;Hello world&#39;);
$redis->setRange(&#39;key&#39;, 6, "redis");
$redis->get(&#39;key&#39;);
Copy after login

strlen

得到key的string的长度

$redis->strlen(&#39;key&#39;);
Copy after login

getBit/setBit

返回2进制信息

zset(sorted set)操作相关

zAdd(key, score, member):向名称为key的zset中添加元素member,score用于排序。如果该元素已经存在,则根据score更新该元素的顺序。

$redis->zAdd(&#39;key&#39;, 1, &#39;val1&#39;);
$redis->zAdd(&#39;key&#39;, 0, &#39;val0&#39;);
$redis->zAdd(&#39;key&#39;, 5, &#39;val5&#39;);
$redis->zRange(&#39;key&#39;, 0, -1); // array(val0, val1, val5)
Copy after login

zRange(key, start, end,withscores):返回名称为key的zset(元素已按score从小到大排序)中的index从start到end的所有元素

$redis->zAdd(&#39;key1&#39;, 0, &#39;val0&#39;);
$redis->zAdd(&#39;key1&#39;, 2, &#39;val2&#39;);
$redis->zAdd(&#39;key1&#39;, 10, &#39;val10&#39;);
$redis->zRange(&#39;key1&#39;, 0, -1); // with scores $redis->zRange(&#39;key1&#39;, 0, -1, true);
Copy after login

zDelete, zRem

zRem(key, member) :删除名称为key的zset中的元素member

$redis->zAdd(&#39;key&#39;, 0, &#39;val0&#39;);
$redis->zAdd(&#39;key&#39;, 2, &#39;val2&#39;);
$redis->zAdd(&#39;key&#39;, 10, &#39;val10&#39;);
$redis->zDelete(&#39;key&#39;, &#39;val2&#39;);
$redis->zRange(&#39;key&#39;, 0, -1);
Copy after login

zRevRange(key, start, end,withscores):返回名称为key的zset(元素已按score从大到小排序)中的index从start到end的所有元素.withscores: 是否输出socre的值,默认false,不输出

$redis->zAdd(&#39;key&#39;, 0, &#39;val0&#39;);
$redis->zAdd(&#39;key&#39;, 2, &#39;val2&#39;);
$redis->zAdd(&#39;key&#39;, 10, &#39;val10&#39;);
$redis->zRevRange(&#39;key&#39;, 0, -1); // with scores $redis->zRevRange(&#39;key&#39;, 0, -1, true);
zRangeByScore, zRevRangeByScore
$redis->zRangeByScore(key, star, end, array(withscores, limit ));
Copy after login

返回名称为key的zset中score >= star且score <= end的所有元素

zCount

$redis->zCount(key, star, end);
Copy after login

返回名称为key的zset中score >= star且score <= end的所有元素的个数

zRemRangeByScore, zDeleteRangeByScore
$redis->zRemRangeByScore(&#39;key&#39;, star, end);
Copy after login

删除名称为key的zset中score >= star且score <= end的所有元素,返回删除个数

zSize, zCard

返回名称为key的zset的所有元素的个数

zScore

$redis->zScore(key, val2);
Copy after login

返回名称为key的zset中元素val2的score

zRank, zRevRank

$redis->zRevRank(key, val);
Copy after login

返回名称为key的zset(元素已按score从小到大排序)中val元素的rank(即index,从0开始),若没有val元素,返回“null”。zRevRank 是从大到小排序

zIncrBy

$redis->zIncrBy(&#39;key&#39;, increment, &#39;member&#39;);
Copy after login

如果在名称为key的zset中已经存在元素member,则该元素的score增加increment;否则向集合中添加该元素,其score的值为increment

zUnion/zInter

参数

keyOutput

arrayZSetKeys

arrayWeights

aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zUnion.

对N个zset求并集和交集,并将最后的集合保存在dstkeyN中。对于集合中每一个元素的score,在进行AGGREGATE运算前,都要乘以对于的WEIGHT参数。如果没有提供WEIGHT,默认为1。默认的AGGREGATE是SUM,即结果集合中元素的score是所有集合对应元素进行SUM运算的值,而MIN和MAX是指,结果集合中元素的score是所有集合对应元素中最小值和最大值。

Hash操作

hSet

$redis->hSet(&#39;h&#39;, &#39;key1&#39;, &#39;hello&#39;);
Copy after login

向名称为h的hash中添加元素key1—>hello

hGet

$redis->hGet(&#39;h&#39;, &#39;key1&#39;);
Copy after login

返回名称为h的hash中key1对应的value(hello)

hLen

$redis->hLen(&#39;h&#39;);
Copy after login

返回名称为h的hash中元素个数

hDel

$redis->hDel(&#39;h&#39;, &#39;key1&#39;);
Copy after login

删除名称为h的hash中键为key1的域

hKeys

$redis->hKeys(&#39;h&#39;);
Copy after login

返回名称为key的hash中所有键

hVals

$redis->hVals(&#39;h&#39;)
Copy after login

返回名称为h的hash中所有键对应的value

hGetAll

$redis->hGetAll(&#39;h&#39;);
Copy after login

返回名称为h的hash中所有的键(field)及其对应的value

hExists

$redis->hExists(&#39;h&#39;, &#39;a&#39;);
Copy after login

名称为h的hash中是否存在键名字为a的域

hIncrBy

$redis->hIncrBy(&#39;h&#39;, &#39;x&#39;, 2);
Copy after login

将名称为h的hash中x的value增加2

hMset

$redis->hMset(&#39;user:1&#39;, array(&#39;name&#39; => &#39;Joe&#39;, &#39;salary&#39; => 2000));
Copy after login

向名称为key的hash中批量添加元素

hMGet

$redis->hmGet(&#39;h&#39;, array(&#39;field1&#39;, &#39;field2&#39;));
Copy after login

返回名称为h的hash中field1,field2对应的value

redis 操作相关

flushDB

清空当前数据库

flushAll

清空所有数据库

randomKey

随机返回key空间的一个key

$key = $redis->randomKey();
Copy after login

select

选择一个数据库

move

转移一个key到另外一个数据库

$redis->select(0); // switch to DB 0
$redis->set(&#39;x&#39;, &#39;42&#39;); // write 42 to x
$redis->move(&#39;x&#39;, 1); // move to DB 1
$redis->select(1); // switch to DB 1
$redis->get(&#39;x&#39;); // will return 42
Copy after login

rename, renameKey

给key重命名

$redis->set(&#39;x&#39;, &#39;42&#39;);
$redis->rename(&#39;x&#39;, &#39;y&#39;);
$redis->get(&#39;y&#39;); // → 42
$redis->get(&#39;x&#39;); // → `FALSE`
Copy after login

renameNx

与remane类似,但是,如果重新命名的名字已经存在,不会替换成功

setTimeout, expire

设定一个key的活动时间(s)

$redis->setTimeout(&#39;x&#39;, 3);
Copy after login

expireAt

key存活到一个unix时间戳时间

$redis->expireAt(&#39;x&#39;, time() + 3);
Copy after login

keys, getKeys

返回满足给定pattern的所有key

$keyWithUserPrefix = $redis->keys(&#39;user*&#39;);
Copy after login

dbSize

查看现在数据库有多少key

$count = $redis->dbSize();
Copy after login

auth

密码认证

$redis->auth(&#39;foobared&#39;);
Copy after login

bgrewriteaof

使用aof来进行数据库持久化

$redis->bgrewriteaof();
Copy after login

slaveof

选择从服务器

$redis->slaveof(&#39;10.0.1.7&#39;, 6379);
Copy after login

save

将数据同步保存到磁盘

bgsave

将数据异步保存到磁盘

lastSave

返回上次成功将数据保存到磁盘的Unix时戳

info

返回redis的版本信息等详情

type

返回key的类型值

string: Redis::REDIS_STRING
set: Redis::REDIS_SET
list: Redis::REDIS_LIST
zset: Redis::REDIS_ZSET
hash: Redis::REDIS_HASH
other: Redis::REDIS_NOT_FOUND
Copy after login
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template