PHP Connection Redis operation function

Source: Internet
Author: User
Tags redis version

Phpredis is an extension of PHP, the efficiency is quite high with the list sorting function, to create a memory-level module business relationship

This is useful for Redis's official command:

As follows:

Https://github.com/owlient/phpredis (Redis 2.0.4 supported)


Redis::__construct constructor function
$redis = new Redis ();

Connect, open link Redis service
Parameters
Host
: String, service address
Port
: int, port number
Timeout
: float, link length (optional, default = 0, unlimited link time)
Note: There is also time in redis.conf, default is 300

Pconnect, Popen does not actively close the link
Refer to above

SetOption Setting up Redis mode

GetOption viewing the mode of Redis settings

Ping View connection Status

Get gets the value of a key (string value)
If the key does not exist, return false

Set writes key and value (string value)
If the write succeeds, return ture

Setex with time-to-live write value
$redis->setex (' key ', 3600, ' value '); Sets Key→value, with 1h TTL.

Setnx determine if duplicate, write value
$redis->setnx (' key ', ' value ');
$redis->setnx (' key ', ' value ');

Delete Deletes the value of the specified key
Returns the number of keys that have been deleted (long integers)
$redis->delete (' Key1 ', ' key2 ');
$redis->delete (Array (' Key3 ', ' key4 ', ' key5 '));

Ttl
Get a key to the time of survival

Persist
Remove key for lifetime expiration
If the key expires true if it does not expire false

Mset (Redis version 1.1 or above only available)
Assign values to multiple keys at the same time
$redis->mset (Array (' key0 ' = ' value0 ', ' key1 ' = ' value1 '));



Multi, exec, discard
Enter or exit Transaction mode
Parameter optional Redis::multi or Redis::P ipeline. Default is Redis::multi
Redis::multi: Perform multiple operations as one transaction
Redis::P ipeline: Let (multiple) execute commands in a simple, faster way to send to the server, but without any guarantee of atomicity
Discard: Deleting a transaction
return value
multi (), returns a Redis object and enters Multi-mode mode, and once it enters multi-mode mode, all subsequent calls to the method will return the same object, only to the Exec () method being called.

Watch, Unwatch (after the code test, can not achieve the said effect)
Monitor if the value of a key is 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, List of a pair of keys
$redis->watch (' x ');

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


Subscribe *
Method callback. Note that this approach may change in the future

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

Exists
Determine if key exists. Presence true not false

INCR, Incrby
The value in key is increased by 1, and if the second argument is filled in, the value that is filled in the second parameter is added
$redis->incr (' Key1 ');
$redis->incrby (' Key1 ', 10);

DECR, Decrby
Do subtraction, use the same method as incr

GetMultiple
Pass the reference
An array of key elements
return parameters
If key exists return value, there is no 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);

List related actions
Lpush
$redis->lpush (key, value);
Add an element of value to the left (header) of the list with the name key

Rpush
$redis->rpush (key, value);
Add an element of value to the right (tail) of the list named key

Lpushx/rpushx
$redis->lpushx (key, value);
Add a value to the left (head)/Right (tail) of the list with the name key, and if value already exists, do not add

Lpop/rpop
$redis->lpop (' key ');
The output name is the first element of the list from the left (head)/Right (tail) of key, deleting the element

Blpop/brpop
$redis->blpop (' Key1 ', ' Key2 ', 10);
The block version of the Lpop command. That is, when timeout is 0 o'clock, if it encounters a name of keyIList does not exist or the list is empty, the command ends. If timeout>0, if this is the case, wait for timeout seconds, and if the problem is not resolved, the keyi+1Start a list to perform a pop operation

Lsize
$redis->lsize (' key ');
Returns the number of elements for a list with the name key

LIndex, LGet
$redis->lget (' key ', 0);
Returns the element of the index position in the list with the name key

LSet
$redis->lset (' key ', 0, ' X ');
Assigns the element of the index position in the list named key to value

Lrange, Lgetrange
$redis->lrange (' Key1 ', 0,-1);
Returns the element between start and end in the list named key (end is-1, returns all)

LTrim, Listtrim
$redis->ltrim (' key ', start, end);
Intercepts the list named key, preserving the element between start and end

Lrem, Lremove
$redis->lrem (' key ', ' A ', 2);
Remove the count of the elements in the list with the name key as value. Count is 0, removing all elements that value is count>0, removing the element with count values of value from start to finish, count<0 the element that |count| value is removed from the end of a header

Linsert
In the list named key, find the valuePivotValue, and according to the parameter Redis::before | Redis::after, to make sure that the newvalue is placed in front of the pivot, or behind. 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
Returns and removes the tail element of the list named Srckey and adds the element to the head of 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
Adds an element value to a set named key, if value exists, does not write, return false
$redis->sadd (key, value);

Srem, Sremove
Delete the element in the set named key value
$redis->sadd (' Key1 ', ' Set1 ');
$redis->sadd (' Key1 ', ' Set2 ');
$redis->sadd (' Key1 ', ' set3 ');
$redis->srem (' Key1 ', ' Set2 ');

Smove
Move the value element from a collection named Srckey to a collection named Dstkey
$redis->smove (Seckey, Dstkey, value);

Sismember, Scontains
Find if there is a value element in the collection named key, there is ture no false
$redis->sismember (key, value);

SCard, Ssize
Returns the number of elements of a set with the name key

SPop
Randomly returns and deletes an element in a set with the name key

Srandmember
Randomly returns an element in the set named key, without deleting

SInter
Ask for Intersection

Sinterstore
To find the intersection and save the intersection to the collection of output
$redis->sinterstore (' Output ', ' key1 ', ' key2 ', ' Key3 ')

Sunion
Seek and set
$redis->sunion (' S0 ', ' s1 ', ' S2 ');
S0,S1,S2 simultaneous request and set

Sunionstore
To set and save the Assembly to the set of output
$redis->sunionstore (' Output ', ' key1 ', ' key2 ', ' Key3 ');

Sdiff
Finding the difference set

Sdiffstore
Finding the difference set and saving the difference set to the set of output

Smembers, Sgetmembers
Returns all elements of a set with a name of key

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 from the original key and writes value to key
$redis->set (' x ', ' 42 ');
$exValue = $redis->getset (' x ', ' lol '); Return ' A ', replaces x by ' LOL '
$newValue = $redis->get (' x ') '//return ' LOL '

Append
String, the value of string with the name key appended with value
$redis->set (' key ', ' value1 ');
$redis->append (' key ', ' value2 ');
$redis->get (' key ');

GetRange (method does not exist)
Returns the character between start and end in a string named key
$redis->set (' key ', ' string value ');
$redis->getrange (' key ', 0, 5);
$redis->getrange (' key ',-5,-1);

SetRange (method does not exist)
The character between start and end in a string that changes key is value
$redis->set (' key ', ' Hello World ');
$redis->setrange (' key ', 6, "Redis");
$redis->get (' key ');

Strlen
The length of the string that gets the key
$redis->strlen (' key ');

Getbit/setbit
Returns 2 binary information

Zset(Sorted Set) operation-related
Zadd(key, score, member): Adds element Member,score to the zset named key 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 of index from start to end in Zset with the name key (the element has been sorted by score from small to large)
$redis->zadd (' Key1 ', 0, ' val0 ');
$redis->zadd (' Key1 ', 2, ' val2 ');
$redis->zadd (' Key1 ', ten, ' Val10 ');
$redis->zrange (' Key1 ', 0,-1); With scores $redis->zrange (' Key1 ', 0,-1, true);

ZDelete, Zrem
Zrem(key, member): Delete the element in the Zset named Key member
$redis->zadd (' key ', 0, ' val0 ');
$redis->zadd (' key ', 2, ' val2 ');
$redis->zadd (' key ', ten, ' Val10 ');
$redis->zdelete (' key ', ' val2 ');
$redis->zrange (' key ', 0,-1);

Zrevrange(key, start, end,Withscores): Returns all elements of index from start to end in Zset with the name key (the element has been sorted by score from large to small).Withscores: Output socre value, default false, no output
$redis->zadd (' key ', 0, ' val0 ');
$redis->zadd (' key ', 2, ' val2 ');
$redis->zadd (' key ', ten, ' 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 of score >= star and score <= end in Zset named key

Zcount
$redis->zcount (key, star, end);
Returns the number of all elements in the Zset named key score >= star and score <= end

Zremrangebyscore, Zdeleterangebyscore
$redis->zremrangebyscore (' key ', star, end);
Delete all elements of score >= star and score <= end in Zset named Key, returning the number of deletions

Zsize, Zcard
Returns the number of all elements of a zset named key

Zscore
$redis->zscore (key, Val2);
Returns the score of element Val2 in Zset with the name key

Zrank, Zrevrank
$redis->zrevrank (Key, Val);
Returns the rank (that is, index, starting at 0) of the Val element in the Zset with the name key (the element has been sorted score from small to large), and returns "NULL" if there is no Val element. Zrevrank is sorted from big to small

Zincrby
$redis->zincrby (' key ', increment, ' member ');
If the element member is already present in the Zset with the name key, the score of the element increases increment; otherwise, the element is added to the collection and its score value is increment

Zunion/zinter
Parameters
KeyOutput
Arrayzsetkeys
Arrayweights
AggregateFunction
Either "SUM", "MIN", or "MAX": Defines the behaviour to use on duplicate entries during the zunion.
Sets and intersects the N Zset, and saves the final collection in Dstkeyn. For the score of each element in a collection, multiply the weight parameter for the aggregate operation before doing it. 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 value of the sum operation for all the corresponding elements of the collection, while Min and Max means that the score of the elements in the result set are the minimum and maximum values in the corresponding elements of all the collections.

HashOperation
Hset
$redis->hset (' h ', ' key1 ', ' hello ');
Add an element to a hash named H Key1->hello

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

Hlen
$redis->hlen (' h ');
Returns the number of elements in a hash with the name H

Hdel
$redis->hdel (' h ', ' key1 ');
Delete a field with a hash key of Key1 named H

Hkeys
$redis->hkeys (' h ');
Returns all keys in a hash with the name key

Hvals
$redis->hvals (' h ')
Returns the value of all keys in a hash with the name H

Hgetall
$redis->hgetall (' h ');
Returns all keys (field) and their corresponding value in a hash with the name H

Hexists
$redis->hexists (' h ', ' a ');
Whether there is a field with the key name A in the hash with the name H

Hincrby
$redis->hincrby (' h ', ' X ', 2);
Adds 2 to the value of x in the hash named H

Hmset
$redis->hmset (' user:1 ', Array (' name ' = ' Joe ', ' salary ' = 2000));
Add elements in bulk to a hash named key

Hmget
$redis->hmget (' h ', Array (' field1 ', ' field2 '));
Returns the value of Field1,field2 corresponding to the hash named H

Redis Operations Related
Flushdb
Empty the current database

Flushall
Clear all databases

Randomkey
Randomly returns a key in the key space
$key = $redis->randomkey ();

Select
Select a database
Move
Transfer a key to another database
$redis->select (0); Switch to DB 0
$redis->set (' x ', ' 42 '); Write to X
$redis->move (' x ', 1); Move to DB 1
$redis->select (1); Switch to DB 1
$redis->get (' x '); would 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, however, if the renamed name already exists, it will not replace the successful

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
Returns all keys that satisfy a given pattern
$keyWithUserPrefix = $redis->keys (' user* ');

Dbsize
See how many keys are in the database now
$count = $redis->dbsize ();

Auth
Password Authentication
$redis->auth (' foobared ');

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

Slaveof
Select from server
$redis->slaveof (' 10.0.1.7 ', 6379);

Save
Save data to disk synchronously

Bgsave
Asynchronously saves data to disk

Lastsave
Returns the UNIX timestamp when the data was last successfully saved to disk

Info
Returns details such as version information for Redis



Type
Returns 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

Good text to the top concern me to collect the article

PHP Connection Redis operation function

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.