Redis
Keyword
-
KEYS pattern
(glob wildcard)- ? any char
- * any chars
- [a-z] scope
- \x x
-
EXISTS key
if exists return 1 else return 0 (integer) -
DEL key
[key …] return the count of the keys deleted -
TYPE key
get the type of the key- return string,hash,list,set,zset
String
- max 512MB
SET key
GET key
INCR key
increase integerDECR key
decrease integerINCRBY key increment
INCRBYFLOAT
increase floatAPPEND key value
append at the endSTRLEN key
xxx return the length of the key if key not exists return 0 (UTF-8 one Chinese char is 3)MGET key [key ...]
get many keys at the same timeMSET key value [key value ...]
GETBIT key offset
SETBIT key offset value
BITCOUNT key [start] [end]
get the num of binary bit 1 start and end refer byteBITOP operation destkey key [key ...]
bit operation result is destkey
BITOPS key 0/1 [start] [end]
get the first position of 0/1
Hash
HSET key field value
HGET key field
HMSET key field value [field value ...]
HMGET key field [field ...]
HGETALL key
HEXISTS key field
HSETNX key field value
if key exists do nothingHINCRBY key field increment
HDEL key field [field ..]
return the num of deleted fieldedHKEYS key
get all field names without valuesHVALS key
get all field values without namesHLEN key
get the num of fields
List
LPUSH key value [value ...]
push on leftRPUSH key value [value ...]
push on rightLPOP key
RPOP key
LLEN key
get lengthLRANGE key start stop
get a range from start to stop (support negative number)LREM key count value
delete count members values value if count > 0 begin on left, < 0 begin on right, = 0 delete allLINDEX key index
get the value specified by indexLSET key index value
set valueLTRIM key start end
only save the specified membersLINSERT key BEFORE|AFTER pivot value
return the length of the listRPOPLPUSH source destination
rpop from source to lpush destinationBRPOP
block
Set
- MAX 2^32-1 hash table
SADD key member [member ...]
SREM key member [member ...]
removeSMEMBERS key
get all membersSISMEMBER key member
judge if existSDIFF key [key ,,]
difference operationSINTER key [key ,,]
intersection operationSUNION key [key ,,]
union operationSCARD key
get the num of members of the setSDIFFSTORE destination key [key ...]
storage the resultSINTERSTORE destination key [key ...]
SUNIONSTORE destination key [key ...]
SRANDMEMBER key [count]
get count members randomly if count is negative return repeatable membersSPOP key
pop randomly
Zset
ZADD key score member [score member ...]
ZSCORE key member
get the score of the memberZRANGE key start stop [WITHSCORES]
get scores from small to largeZREVRANGE key start stop [WITHSCORES]
from large to smallZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
if wants the result without point add ( before min maxZREVRANGEBYSCORE key min max [WITHSCORE] [LIMIT offset count]
ZINCRBY key increment member
ZCARD key
get the num of zsetZCOUNT key min max
ZREM ket member [member ...]
ZREMRANGEBYRANK ket start stop
from small to largeZREMRANGEBYSCORE key min max
ZRANK key member
get rankZREVRANK key member
Advanced
Transaction
-
MULTI
the start of a transaction -
EXEC
the end of a transaction -
handle error
- grammar error: all commands won’t be executed
- run error: other commands will be executed
redis doesn’t support rollback
-
WATCH
can watch one or more keys, if one of them was changed, the transaction won’t be executed
UNWATCH
cancel watch
Expiration
EXPIRE key seconds
if success return 1, else return 0TTL key
get the time left of the key if the key doesn’t have a expiration return -1, else if the key doesn’t exist return -2PERSIST key
cancel the expiration SET and GETSET will also clear expirationPEXPORE key milliseconds
EXPIREAT key unixtime
PEXPOREAT key unixtime
Sort
SORT key [LIMIT start end] [BY prefix:* (-> field)] [GET prefix:* (->field)] [STORE key]
- a SORT can have many GET parameters
GET #
return the main key
Message
LPOP key [key ...] [timeout]
priorityPUBLISH channel msg
SUBSCRIBE channel
after executing SUBSCRIBE will enter publish and subscribe modeUNSUBSCRIBE channel
PSUBSCRIBE channle(glob)
PUNSUBSCRIBE channel(glob)
Script
Lua
-
data type
- nil
- boolean
- number
- string
- table
- function
-
variable
-
default is nil
-
global variable (cannot be used in redis)
a = 1
assign 1 to the variablea = nil
delete a variable
-
local variable
-
local c
declare a variable -
local d = 1
declare and assign a variable -
local e,f
declare many variables at the same time -
save a function to a variable
local say_hi = function () print 'hi' end
-
local variable’s scope begins from the declaration, ends with the layer
-
-
comment
- one line
--
- multi-line
--[[ comment ]]
- one line
-
assign
local a, b = 1, 2
a=1 b=2local c, d = 1, 2, 3
c=1 d=2local e, f = 1
e=1, f=nil- as executing multiple assignment Lua will calculate expression’s value
-
operator
+ - * / % ^
number string will be changed to number== ~= < > <= >=
string cannot be transformed to numbernot and or
0 is..
connect two string#
get the size of string or table
-
if
if expression then ... elseif expression then ... else ... end
-
cycle
while expression do ... end repeat ... until expression for variable = initial, endvalue, step(default = 1) do ... end for variable1, variable2, ..., vraiableN in literator do .. end
-
table
a = {}
a['filed'] = 'value'
- index is from 1
ipairs()
like a literatorpairs()
traverse the table not array
-
function
function (list of parameters) ... return end local function name (list of patters) return end
...
in () means many parameters
-
-
standard library
Redis support Base String Table Math Debug
- String lib
string.len(string)
get the length of the stringstring.lower(string)
string.upper(string)
convert the casestring.sub(string start [end default = -1])
get the substring
- Table lib
table.concat(table [sep] [i] [j])
toStringtable.insert(table [pos default=length+1] value)
table.remove(table [pos default=length])
pop a element
- Math lib
- abs sin cos tan ceil floor max min pow sqrt random random seed
- other libs
- cjson.encode(table)
- cjson.decode(string)
- cmsgpack.pack(table)
- cmsgpack.unpack(string)
- String lib
-
Redis with Lua
redis return value Lua data type integer number string string multi-line string table status table(only a ok field) error table(only a err field) EVAL script keyNum [key ...] [arg ...]
through KEYS ARGV to get the parametersEVALSHA
-
KEYS and ARGV
- KEYS refers to key names
- ARGV refers to not key names
-
other commands about scripts
SCRIPT LOAD script
load script to cacheSCRIPT EXISTS script [scripts...]
judge if the script cachedSCRIPT FLUSH
clear scriptsSCRIPT KILL
kill script
Persistence
RDB
SAVE m n
m is time, n is in the time changed key numberSAVE
BGSAVE
save in backgroundLASTSAVE
get the lastest snapshot timeFLUSHALL
clear all data and if hte auto save is not null, will snapshot
AOF
appendonly yes
Cluster
Replication
Design And Implementation
Simple Dynamic String
save string, use as buffer: AOF buffer, client input buffer
struct sdshdr{
int len;
int free;
char buf[]
}
- O(1) get string length
- avoid buffer overflow
- reduce the number of memory reallocations required to modify the length of a string
- binary security
- compatible with part of
C
string function
Link List
one of list key’s implementation, publish and subscribe, slow search, monitor
typedef struct list{
listNode *head;
listNode *tail
unsigned long len;
void *(*dup) (vpid *ptr); //copy
void (*free) (void *ptr);
int (*match) (void *ptr, void *key);
}
Dictionary
redis database, hash key
typedef struct dictht{
dicEntry **table;
unsigned long size;
unsigned long sizemask;
unsigned long used;
}