Redis
Keyword
-
KEYS pattern(glob wildcard)- ? any char
- * any chars
- [a-z] scope
- \x x
-
EXISTS keyif exists return 1 else return 0 (integer) -
DEL key[key …] return the count of the keys deleted -
TYPE keyget the type of the key- return string,hash,list,set,zset
String
- max 512MB
SET keyGET keyINCR keyincrease integerDECR keydecrease integerINCRBY key incrementINCRBYFLOATincrease floatAPPEND key valueappend at the endSTRLEN keyxxx 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 valueHGET key fieldHMSET key field value [field value ...]HMGET key field [field ...]HGETALL keyHEXISTS key fieldHSETNX key field valueif key exists do nothingHINCRBY key field incrementHDEL key field [field ..]return the num of deleted fieldedHKEYS keyget all field names without valuesHVALS keyget all field values without namesHLEN keyget the num of fields
List
LPUSH key value [value ...]push on leftRPUSH key value [value ...]push on rightLPOP keyRPOP keyLLEN keyget lengthLRANGE key start stopget a range from start to stop (support negative number)LREM key count valuedelete count members values value if count > 0 begin on left, < 0 begin on right, = 0 delete allLINDEX key indexget the value specified by indexLSET key index valueset valueLTRIM key start endonly save the specified membersLINSERT key BEFORE|AFTER pivot valuereturn the length of the listRPOPLPUSH source destinationrpop from source to lpush destinationBRPOPblock
Set
- MAX 2^32-1 hash table
SADD key member [member ...]SREM key member [member ...]removeSMEMBERS keyget all membersSISMEMBER key memberjudge if existSDIFF key [key ,,]difference operationSINTER key [key ,,]intersection operationSUNION key [key ,,]union operationSCARD keyget 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 keypop randomly
Zset
ZADD key score member [score member ...]ZSCORE key memberget 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 memberZCARD keyget the num of zsetZCOUNT key min maxZREM ket member [member ...]ZREMRANGEBYRANK ket start stopfrom small to largeZREMRANGEBYSCORE key min maxZRANK key memberget rankZREVRANK key member
Advanced
Transaction
-
MULTIthe start of a transaction -
EXECthe 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
-
WATCHcan watch one or more keys, if one of them was changed, the transaction won’t be executed
UNWATCHcancel watch
Expiration
EXPIRE key secondsif success return 1, else return 0TTL keyget 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 keycancel the expiration SET and GETSET will also clear expirationPEXPORE key millisecondsEXPIREAT 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 msgSUBSCRIBE channelafter executing SUBSCRIBE will enter publish and subscribe modeUNSUBSCRIBE channelPSUBSCRIBE 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 = 1assign 1 to the variablea = nildelete a variable
-
local variable
-
local cdeclare a variable -
local d = 1declare and assign a variable -
local e,fdeclare 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, 2a=1 b=2local c, d = 1, 2, 3c=1 d=2local e, f = 1e=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 or0 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 scriptload script to cacheSCRIPT EXISTS script [scripts...]judge if the script cachedSCRIPT FLUSHclear scriptsSCRIPT KILLkill script
Persistence
RDB
SAVE m nm is time, n is in the time changed key numberSAVEBGSAVEsave in backgroundLASTSAVEget the lastest snapshot timeFLUSHALLclear 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
Cstring 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;
}