Php-redis Chinese Document Introduction _php Tips

Source: Internet
Author: User
Tags auth key string redis redis version
phpredis is an extension of php, the efficiency is quite high, it has a linked list sorting function, and it can create module-level business relationships

Very useful; here are the command usage tips provided by redis official:

The download address is as follows:

https://github.com/owlient/phpredis (supports redis 2.0.4)

Redis :: __ construct constructor
$ redis = new Redis ();

connect, open
parameter
host: string, service address
port: int
timeout: float, link duration (optional, default is 0, unlimited link time)
Note: There is also time in redis.conf, default is 300

pconnect, popen does not actively close links
See above

setOption set 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 key and value (string value)
If the write is successful, return ture

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

setnx determines whether to repeat, write value
$ redis-> setnx ('key', 'value');
$ redis-> setnx ('key', 'value');

delete delete the value of the specified 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 whose lifetime has expired
If key expires true if not expires false

mset (only available in redis version 1.1 and above)
Assign multiple keys at the same time
$ redis-> mset (array ('key0' => 'value0', 'key1' => 'value1'));



multi, exec, discard
Enter or exit transaction mode
Parameters can be Redis :: MULTI or Redis :: PIPELINE. The default is Redis :: MULTI
Redis :: MULTI: Perform multiple operations as one transaction
Redis :: PIPELINE: Makes (multiple) execution commands simple and faster to send to the server, but without any guarantee of atomicity
discard: delete a transaction
return value
multi (), returns a redis object, and enters multi-mode mode. Once in multi-mode mode, all methods called later will return the same object, only until the exec () method is called.

watch, unwatch (after the code test, the stated effect cannot be achieved)
Monitors whether a key value has been changed by another program. 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 keys
$ redis-> watch ('x');

$ ret = $ redis-> multi ()-> incr ('x')-> exec ();


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

publish *
Post content to a certain channel. Note that this method may change in the future

exists
Determine if the key exists. Exists true not false

incr, incrBy
The value in key is incremented by 1. If the second parameter is filled, the value filled by the second parameter is incremented.
$ redis-> incr ('key1');
$ redis-> incrBy ('key1', 10);

decr, decrBy
Do subtraction, use the same method as incr

getMultiple
Passing parameters
An array of keys
Return parameter
Returns value if key exists, false if not present
$ 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);

List-related operations
lPush
$ redis-> lPush (key, value);
Add a value element to the left (head) of the list named key

rPush
$ redis-> rPush (key, value);
Add a value element to the right (tail) of the list named key

lPushx / rPushx
$ redis-> lPushx (key, value);
Add a value element to the left (head) / right (tail) of the list named key, if value already exists, do not add

lPop / rPop
$ redis-> lPop ('key');
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);
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, wait for timeout seconds when the above situation is encountered. If the problem is not resolved, perform a pop operation on the list starting from keyi 1.

lSize
$ redis-> lSize ('key');
Returns how many elements of the list named key

lIndex, lGet
$ redis-> lGet ('key', 0);
Returns the element at index position in a list named key

lSet
$ redis-> lSet ('key', 0, 'X');
Assign the element at the index position in the list named key to value

lRange, lGetRange
$ redis-> lRange ('key1', 0, -1);
Returns the elements in the list named key between start and end (end is -1, return all)

lTrim, listTrim
$ redis-> lTrim ('key', start, end);
Intercept a list named key, keeping elements from start to end

lRem, lRemove
$ redis-> lRem ('key', 'A', 2);
Delete count elements whose value is in the list named key. count is 0, delete all elements with value, count> 0 delete count elements with value from start to end, count <0 delete from end to end with count element with value

lInsert
In the list named key, find the value whose value is pivot, and determine according to the parameter Redis :: BEFORE | Redis :: AFTER that newvalue is placed before or after pivot. If key does not exist, it will not be inserted. If 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 remove the tail element of the list named srckey and add that element to the head of the list named dstkey
$ 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
Add element value to the set named key, if value exists, do not write, return false
$ redis-> sAdd (key, value);

sRem, sRemove
Delete the element value in the set named key
$ redis-> sAdd ('key1', 'set1');
$ redis-> sAdd ('key1', 'set2');
$ redis-> sAdd ('key1', 'set3');
$ redis-> sRem ('key1', 'set2');

sMove
Move the value element from the collection named srckey to the collection named dstkey
$ redis-> sMove (seckey, dstkey, value);

sIsMember, sContains
Find whether there is a value element in the collection named key, whether there is true or false
$ redis-> sIsMember (key, value);

sCard, sSize
Returns the number of elements of the set named key

sPop
Randomly return and delete an element in the set named key

sRandMember
Randomly return an element in the set named key without deleting

sInter
Intersection

sInterStore
Find the intersection and save the intersection to the set of outputs
$ redis-> sInterStore ('output', 'key1', 'key2', 'key3')

sUnion
Union set
$ redis-> sUnion ('s0', 's1', 's2');
s0, s1, s2 simultaneous union set

sUnionStore
Find the union and save the union to the output set
$ redis-> sUnionStore ('output', 'key1', 'key2', 'key3');

sDiff
Difference set

sDiffStore
Find the difference set and save the difference set to the output set

sMembers, sGetMembers
Returns all elements of the set named key

sort
Sorting, pagination, etc.
parameter
'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 the 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 value of the string named key followed by value
$ redis-> set ('key', 'value1');
$ redis-> append ('key', 'value2');
$ redis-> get ('key');

getRange (method does not exist)
Returns the characters from start to end in the string named key
$ redis-> set ('key', 'string value');
$ redis-> getRange ('key', 0, 5);
$ redis-> getRange ('key', -5, -1);

setRange (method does not exist)
Change the characters between start and end in the key string to value
$ redis-> set ('key', 'Hello world');
$ redis-> setRange ('key', 6, "redis");
$ redis-> get ('key');

strlen
Get the length of the key's string
$ redis-> strlen ('key');

getBit / setBit
Returns binary information

zset (sorted set) operation related
zAdd (key, score, member): add element member to zset named key, score is used for sorting. If the element already exists, the order of the element is updated according to 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 all elements from index to start in zset named key (elements have been sorted by score from smallest to largest)
$ 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 element member in zset named key
$ 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 all elements with index from start to end in a zset named key (elements are sorted by score from largest to smallest). withscores: whether to output the value of socre, default false 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 all elements in a zset named score with score> = star and score <= end

zCount
$ redis-> zCount (key, star, end);
Returns the number of all elements in the zset named score with score> = star and score <= end

zRemRangeByScore, zDeleteRangeByScore
$ redis-> zRemRangeByScore ('key', star, end);
Delete all elements in the zset named score with score> = star and score <= end, return the number of deletions

zSize, zCard
Returns the number of all elements of the zset named key

zScore
$ redis-> zScore (key, val2);
Returns the score of element val2 in zset named key

zRank, zRevRank
$ redis-> zRevRank (key, val);
Returns the rank (ie, index, starting from 0) of the val element in the zset (the elements have been sorted by score from smallest to largest) named key. If there is no val element, it returns "null". zRevRank is sorted from big to small

zIncrBy
$ redis-> zIncrBy ('key', increment, 'member');
If the element member already exists in the zset named key, the score of the element is incremented; otherwise, the element is added to the collection, and its score value is increment

zUnion / zInter
parameter
keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zUnion.
Union and intersect N zsets, and save the final set in dstkeyN. For the score of each element in the set, before performing the AGGREGATE operation, it must be multiplied by the corresponding WEIGHT parameter. If WEIGHT is not provided, it defaults to 1. The default AGGREGATE is SUM, that is, the score of the elements in the result set is the value of the SUM operation of all elements corresponding to the set, and MIN and MAX refer to the score of the elements in the result set is the minimum and maximum values of the corresponding elements in all sets.

Hash operations
hSet
$ redis-> hSet ('h', 'key1', 'hello');
Add element key1—> hello to the hash named h

hGet
$ redis-> hGet ('h', 'key1');
Returns the value corresponding to key1 in the hash named h (hello)

hLen
$ redis-> hLen ('h');
Returns the number of elements in the hash named h

hDel
$ redis-> hDel ('h', 'key1');
Delete the domain with key key1 in the hash named h

hKeys
$ redis-> hKeys ('h');
Returns all keys in the hash named key

hVals
$ redis-> hVals ('h')
Returns the value corresponding to all keys in the hash named h

hGetAll
$ redis-> hGetAll ('h');
Returns all keys in the hash named h and their corresponding values

hExists
$ redis-> hExists ('h', 'a');
Is there a domain with key name a in the hash named h

hIncrBy
$ redis-> hIncrBy ('h', 'x', 2);
Increase the value of x in the hash named h by 2

hMset
$ redis-> hMset ('user: 1', array ('name' => 'Joe', 'salary' => 2000));
Add elements in batches to the hash named key

hMGet
$ redis-> hmGet ('h', array ('field1', 'field2'));
Returns the value corresponding to field1 and field2 in the hash named h

redis operation related
flushDB
Clear the current database

flushAll
Clear all databases

randomKey
Randomly return a key in the key space
$ key = $ redis-> randomKey ();

select
Choose a database
move
Transfer 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 the 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 the active time of a key (s)
$ redis-> setTimeout ('x', 3);

expireAt
key survives to a Unix timestamp time
$ redis-> expireAt ('x', time () + 3);

keys, getKeys
Return all keys that satisfy the given pattern
$ keyWithUserPrefix = $ redis-> keys ('user *');

dbSize
See how many keys the database has now
$ count = $ redis-> dbSize ();

auth
Password authentication
$ redis-> auth ('foobared');

bgrewriteaof
Using aof for database persistence
$ redis-> bgrewriteaof ();

slaveof
Select slave server
$ redis-> slaveof ('10 .0.1.7 ', 6379);

save
Save data to disk synchronously

bgsave
Save data asynchronously to disk

last
Save
Returns the Unix timestamp of the last successful data save to disk

info
Returns details such as redis version information



type
Returns the type value of the 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.