phpredis是php的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务关系
很有用;以下是redis官方提供的命令使用技巧:
下载地址如下:
https://github.com/owlient/phpredis (supports redis 2.0.4)
Redis::__constructConstructor
$redis = new Redis();
connect, open Link redis service
Parameters
host: string, service address
port: int, port number
timeout: float, link duration (optional, default is 0, no Limited link time)
Note: There is also time in redis.conf, the default is 300
pconnect, popen For links that will not be actively closed
refer to the above
setOption Set the redis mode
getOption View the mode set by redis
ping View the connection status
get Get the value of a key (string value)
If the key does not exist, return false
set write Enter 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.
setnx to determine whether it is repeated, write the value
$redis->setnx('key', 'value');
$redis->setnx('key', 'value');
delete Delete the specified The value of key
Returns the number of deleted keys (long integer)
$redis->delete('key1', 'key2');
$redis->delete(array('key3 ', 'key4', 'key5'));
ttl
Get the survival time of a key
persist
Remove keys with expired lifetime
true if key expires false if not expired
mset (redis version 1.1 or above only available)
give to multiple at the same time key assignment
$redis->mset(array('key0' => 'value0', 'key1' => 'value1'));
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: Let (multiple) execution commands be sent to the server simply and faster, but without any atomicity guarantee
discard: Delete one Transaction
Return Value
multi(), returns a redis object and enters multi-mode mode. Once entering multi-mode mode, all methods called in the future will return the same object until the exec() method is called. call.
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 Cancel all keys monitored by this program
Parameter, a list of key pairs
$redis->watch('x');
$ret = $redis->multi() ->incr('x') ->exec();
subscribe *
method callback. Note that this method may change in the future
publish *
Publish content to a 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);
decr, decrBy
does 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 not, 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);
listRelated operations
lPush
$redis->lPush(key, value);
is in the listkey >Add a element >rPush
$redis->rPush(key, value); in the
key
Add a element with the value value to the right (tail) of 🎜>list lPushx/rPushx
$redis->lPushx(key, value); in the name key
's list on the left (head)/ on the right (tail) adds a value of value's element, if value already exists, then lPop/rPop
$redis will not be added ->lPop('key');Output the list
left (header) named key Starting from/The first element starting from the right (end) of , delete the element blPop/brPop$ redis->blPop('key1', 'key2', 10);
lpop
block version of the command. That is, when timeout is 0, if the name is key list of 🎜>i does not exist or the list is If empty, the command ends. If timeout>0, when encountering the above situation, wait for timeout seconds, if the problem is not solved, then keyi+1Startedlistexecute popOperationlSize$redis->lSize('key');Return the name of key How many elements does the list have?
lIndex, lGet
$redis->lGet('key', 0);
The return name is
list of 🎜>key in the index position 🎜>lSet$redis->lSet('key', 0, 'X');Give the name
key
The element at the
index
position in list is assigned the value valuelRange, lGetRange$redis->lRange('key1', 0, -1);Return the name of
key
Elements between
start
to end in list (end is -1 , return all) lTrim, listTrim$redis->lTrim('key', start, end
);
Intercept the
list named key
and keep start to endlRem, lRemove$redis->lRem( 'key', 'A', 2);Delete count
with the name
key
>List elements whose value is value.count is 0, delete all elements with value value, count>0Delete count elements with value value from beginning to end, count<0Delete |count| from end to end with value value Element
lInsert
finds the value with value pivot in the list named key, and based on the parameter Redis::BEFORE | Redis::AFTER, to determine whether newvalue is placed before or after pivot.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('key1', 0, -1);
$redis->lInsert('key1', Redis::AFTER, 'C', 'Y');
$redis->lRange('key1', 0, -1);
$redis->lInsert('key1', Redis::AFTER, 'W', 'value');
rpoplpush
Return and delete the name as The tail element of srckey's list and add that element to the name dstkeylist$redis->delete('x', 'y');
$redis->lPush ('x', 'abc'); $redis->lPush('x', 'def'); $redis->lPush('y', '123'); $redis->lPush(' y', '456'); // move the last of x to the front of y. var_dump($redis->rpoplpush('x', 'y'));
var_dump($redis-> lRange('x', 0, -1));
var_dump($redis->lRange('y', 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" }
SET operation related
sAdd
The direction name is key Add element value to 's set. If value exists, do not write it, return false
$redis->sAdd(key, value);
sRem, sRemove
Delete the setkey >Elements in value$redis->sAdd('key1' , 'set1');
$redis->sAdd('key1' , 'set2' );
$redis->sAdd('key1' , 'set3');
$redis->sRem('key1', 'set2');
sMove
moves the value element from the collection named srckey to the set named dstkey$redis->sMove(seckey, dstkey, value);
sIsMember, sContains
Find whether there is a value element in the collection named key, if there is true but not false$redis->sIsMember(key , value);
sCard, sSize
returns the
setkey The number of elements of 🎜>sPop
randomly returns and deletes the name
key An element in setsRandMember
randomly returns the name
key 's set does not delete an element in sInter
to find the intersection
sInterStore
Find the intersection and save the intersection to the collection of output
$redis->sInterStore ('output', 'key1', 'key2', 'key3')
sUnion
Find the union
$redis-> sUnion('s0', 's1', 's2');s0,s1,s2 simultaneously find the union
sUnionStore
find the union Save the union to the set of output
$redis->sUnionStore('output', 'key1', 'key2', 'key3');
sDiff
Find the difference set
sDiffStore
Find the difference set and save the difference set to the set of output
sMembers, sGetMembers
returns the
setkey >All elements of sort
sorting, paging, etc.
parameters
'by' => ' some_pattern_*',
'limit' => array(0, 1),'get' => 'some_other_pattern_*' or an array of patterns,
'sort' => 'asc ' or 'desc','alpha' => TRUE,
'store' => 'external-key'
Example
$redis->delete ('s'); $redis->sadd('s', 5); $redis->sadd('s', 4); $redis->sadd('s', 2); $redis ->sadd('s', 1); $redis->sadd('s', 3);var_dump($redis->sort('s')); // 1,2, 3,4,5
var_dump($redis->sort('s', array('sort' => 'desc'))); // 5,4,3,2,1
var_dump($redis->sort('s', array('sort' => 'desc', 'store' => 'out'))); // (int)5
string command
getSet returns the value in the original key and writes the value to key
$redis->set( 'x', '42');$exValue = $redis->getSet('x', 'lol'); // return '42', replaces x by 'lol'$newValue = $redis->get('x')' // return 'lol'
append
string, the
name is key
The value of string is followed by value$redis->set('key', 'value1'); $redis->append('key', 'value2');$redis->get('key');
getRange
(method does not exist)
returns the string
named
key in start to The characters between end$redis->set('key', 'string value');$redis->getRange('key', 0, 5);$redis->getRange('key', -5, -1);
setRange
(method does not exist)
Change
key The characters between
start
and end in string of are value$redis->set('key', 'Hello world');$redis->setRange('key', 6, "redis");$redis-> get('key');strlen
Get the length of string of key
$redis->strlen('key');
getBit/setBit
Return binary information
zset(sorted set) Operation related
zAdd(key, score, member ): Add element to zset named key member, score are used for sorting. If the element already exists, update the order of the element based on score.
$redis->zAdd('key', 1, 'val1');
$redis->zAdd('key', 0, 'val0');
$redis ->zAdd('key', 5, 'val5');
$redis->zRange('key', 0, -1); // array(val0, val1, val5)
zRange(key, start, end,withscores): Returns the zset named key (the element has been pressed by score sorted from small to large) index from start to end All elements of
$redis->zAdd('key1', 0, 'val0');
$redis->zAdd('key1', 2, 'val2') ;
$redis->zAdd('key1', 10, 'val10');
$redis->zRange('key1', 0, -1); // with scores $redis-> ;zRange('key1', 0, -1, true);
zDelete, zRem
zRem( key, member) : Delete the zset named key Elements in member
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key' , 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zDelete('key', 'val2');
$redis->zRange('key', 0, -1);
zRevRange(key, start, end, withscores): Returns the named key index in zset (elements sorted by score from largest to smallest) All elements from 🎜>start to end.withscores: Whether to output the value of socre, default false, Do not output $redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis- >zAdd('key', 10, 'val10');
$redis->zRevRange('key', 0, -1); // with scores $redis->zRevRange('key', 0, -1, true);
zRangeByScore, zRevRangeByScore$redis->zRangeByScore(key, star, end, array(withscores, limit ));
Returns the zset with the name key score >= starAnd all elements of score <= end
zCount
$redis->zCount(key, star, end);
returns the score > in the zset whose name is key ;= star and score <= end The number of all elements
zRemRangeByScore, zDeleteRangeByScore
$redis->zRemRangeByScore('key', star, end);
Delete the name as keyzset in score >= star and score <= endAll elements of , return the deleted number
zSize, zCard
The returned name is key< The number of all elements of 🎜>zset
zScore
$redis->zScore(key, val2);
returns the element
val2zset named key >'sscorezRank, zRevRank
$redis->zRevRank(key, val);Returns
zset with name key (element has been pressed from small to small by score The rank of the val element in the large sort) (that is, index, from 0 starts), if there is no val element, return "null".zRevRank is sorted from large to small
zIncrBy
$redis->zIncrBy('key', increment, 'member');
If element member already exists in zset with name key >, then the element's score increases by increment; otherwise, the element is added to the set, and its score is increment
zUnion/zInter
ParameterskeyOutput
arrayZSetKeys
arrayWeights
aggregateFunction
Either "SUM", "MIN", or "MAX": defines the behavior to use on duplicate entries during the zUnion .
Find the union and intersection of Nzset, and save the final set in dstkeyN. For each element in the set, the score must be multiplied by the before performing the AGGREGATE operation. >WEIGHT parameter. If WEIGHT is not provided, the default is 1. The default AGGREGATE is SUM, that is, the score of the elements in the result set is The values of the corresponding elements of all sets are SUM, while MIN and MAX It means that the score of the elements in the result set are the minimum and maximum values of the corresponding elements in all sets.
HashOperation
hSet
$redis->hSet('h', 'key1', 'hello');
The direction name is Add element key1—>hello in the hash of >h >
hGet
$redis->hGet('h', 'key1');
Return the name h The value (hello) corresponding to key1 in hash
hLen
$redis->hLen('h');
Returns the hash named h The number of elements in
hDel
$redis->hDel('h', 'key1');
The deleted name is h domain hKeys$redis->hKeys('h');Returns the named
key
Return
value corresponding to all keys in the hash named h
hGetAll$redis->hGetAll('h');
Returns the hash All keys in 🎜> (field) and their corresponding value
hExists
$redis->hExists('h', 'a');
hashhIncrBy$redis->hIncrBy('h', 'x' , 2); will be named h
in hash
in x'svalueincreases2
hMset$redis-> hMset('user:1', array('name' => 'Joe', 'salary' => 2000));
The direction name is key's hashhMGet$redis->hmGet('h', array('field1', 'field2'));returns the hash with the name
h
field1,field2
correspondingvalueredis operation related
flushDB
Clear the current database
flushAllClear all databasesrandomKeyRandomly returns akeyspace
key
$key = $redis->randomKey(); select
Select a database
move
Move a key to another database
$redis->select(0 ); // switch to DB 0$redis->set('x', '42'); // write 42 to x
$redis->move('x', 1); // move to DB 1
$redis->select(1); // switch to DB 1$redis->get('x'); // will return 42
rename, renameKey
Rename key$redis->set('x', '42');$redis->rename('x', 'y');$redis->get('y'); // → 42$redis->get('x'); // → `FALSE`renameNx
Similar to remane, but if the renamed name already exists, it will not be replaced successfully
setTimeout, expire
Set an activity time for key
(
s
)
$redis->setTimeout('x' , 3);
expireAt
key survives to a unix timestamp time
$redis->expireAt('x', time() + 3);
keys, getKeys
returns all
key
pattern 🎜>$keyWithUserPrefix = $redis->keys('user*');dbSizeCheck how many keys there are in the database now$count = $redis-> ;dbSize();
auth
Password authentication$redis->auth('foobared');
bgrewriteaof
Use aof for database persistence$redis->bgrewriteaof();
slaveofSelect the slave server$redis-> slaveof('10.0.1.7', 6379);save
Save data to disk synchronously
bgsave
Asynchronously save data to disk
lastSave
Return to the last successful save of data to disk Unix timestamp
info
returns redis version information and other details
type
Return the type value of 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