深入理解Redis事务

数据库 其他数据库 Redis
Redis可以看成NoSQL类型的数据库系统, Redis也提供了事务, 但是和传统的关系型数据库的事务既有相似性, 也存在区别.

Redis可以看成NoSQL类型的数据库系统, Redis也提供了事务, 但是和传统的关系型数据库的事务既有相似性, 也存在区别.因为Redis的架构基于操作系统的多路复用的IO接口,主处理流程是一个单线程,因此对于一个完整的命令, 其处理都是原子性的, 但是如果需要将多个命令作为一个不可分割的处理序列, 就需要使用事务.

Redis事务有如下一些特点:

  •  事务中的命令序列执行的时候是原子性的,也就是说,其不会被其他客户端的命令中断. 这和传统的数据库的事务的属性是类似的.
  •  尽管Redis事务中的命令序列是原子执行的, 但是事务中的命令序列执行可以部分成功,这种情况下,Redis事务不会执行回滚操作. 这和传统关系型数据库的事务是有区别的.
  •  尽管Redis有RDB和AOF两种数据持久化机制, 但是其设计目标是高效率的cache系统. Redis事务只保证将其命令序列中的操作结果提交到内存中,不保证持久化到磁盘文件. 更进一步的, Redis事务和RDB持久化机制没有任何关系, 因为RDB机制是对内存数据结构的全量的快照.由于AOF机制是一种增量持久化,所以事务中的命令序列会提交到AOF的缓存中.但是AOF机制将其缓存写入磁盘文件是由其配置的实现策略决定的,和Redis事务没有关系.

Redis事务API

从宏观上来讲, Redis事务开始后, 会缓存后续的操作命令及其操作数据,当事务提交时,原子性的执行缓存的命令序列.

从版本2.2开始,Redis提供了一种乐观的锁机制, 配合这种机制,Redis事务提交时, 变成了事务的条件执行. 具体的说,如果乐观锁失败了,事务提交时, 丢弃事务中的命令序列,如果乐观锁成功了, 事务提交时,才会执行其命令序列.当然,也可以不使用乐观锁机制, 在事务提交时, 无条件执行事务的命令序列.

Redis事务涉及到MULTI, EXEC, DISCARD, WATCH和UNWATCH这五个命令:

  •  事务开始的命令是MULTI, 该命令返回OK提示信息. Redis不支持事务嵌套,执行多次MULTI命令和执行一次是相同的效果.嵌套执行MULTI命令时,Redis只是返回错误提示信息.
  •  EXEC是事务的提交命令,事务中的命令序列将被执行(或者不被执行,比如乐观锁失败等).该命令将返回响应数组,其内容对应事务中的命令执行结果.
  •  WATCH命令是开始执行乐观锁,该命令的参数是key(可以有多个), Redis将执行WATCH命令的客户端对象和key进行关联,如果其他客户端修改了这些key,则执行WATCH命令的客户端将被设置乐观锁失败的标志.该命令必须在事务开始前执行,即在执行MULTI命令前执行WATCH命令,否则执行无效,并返回错误提示信息.
  •  UNWATCH命令将取消当前客户端对象的乐观锁key,该客户端对象的事务提交将变成无条件执行.
  •  DISCARD命令将结束事务,并且会丢弃全部的命令序列.

需要注意的是,EXEC命令和DISCARD命令结束事务时,会调用UNWATCH命令,取消该客户端对象上所有的乐观锁key.

无条件提交

如果不使用乐观锁, 则事务为无条件提交.下面是一个事务执行的例子: 

  1. multi  
  2. +OK  
  3. incr key1  
  4. +QUEUED  
  5. set key2 val2  
  6. +QUEUED  
  7. exec  
  8. *2  
  9. :1  
  10. +OK 

当客户端开始事务后, 后续发送的命令将被Redis缓存起来,Redis向客户端返回响应提示字符串QUEUED.当执行EXEC提交事务时,缓存的命令依次被执行,返回命令序列的执行结果.

事务的错误处理

事务提交命令EXEC有可能会失败, 有三种类型的失败场景:

  •  在事务提交之前,客户端执行的命令缓存失败.比如命令的语法错误(命令参数个数错误, 不支持的命令等等).如果发生这种类型的错误,Redis将向客户端返回包含错误提示信息的响应.
  •  事务提交时,之前缓存的命令有可能执行失败.
  •  由于乐观锁失败,事务提交时,将丢弃之前缓存的所有命令序列.

当发生第一种失败的情况下,客户端在执行事务提交命令EXEC时,将丢弃事务中所有的命令序列.下面是一个例子: 

  1. multi  
  2. +OK  
  3. incr num1 num2  
  4. -ERR wrong number of arguments for 'incr' command  
  5. set key1 val1  
  6. +QUEUED  
  7. exec  
  8. -EXECABORT Transaction discarded because of previous errors. 

命令incr num1 num2并没有缓存成功, 因为incr命令只允许有一个参数,是个语法错误的命令.Redis无法成功缓存该命令,向客户端发送错误提示响应.接下来的set key1 val1命令缓存成功.最后执行事务提交的时候,因为发生过命令缓存失败,所以事务中的所有命令序列被丢弃.

如果事务中的所有命令序列都缓存成功,在提交事务的时候,缓存的命令中仍可能执行失败.但Redis不会对事务做任何回滚补救操作.下面是一个这样的例子: 

  1. multi  
  2. +OK  
  3. set key1 val1  
  4. +QUEUED  
  5. lpop key1  
  6. +QUEUED  
  7. incr num1  
  8. +QUEUED  
  9. exec  
  10. *3  
  11. +OK  
  12. -WRONGTYPE Operation against a key holding the wrong kind of value  
  13. :1 

所有的命令序列都缓存成功,但是在提交事务的时候,命令set key1 val1和incr num1执行成功了,Redis保存了其执行结果,但是命令lpop key1执行失败了.

乐观锁机制

Redis事务和乐观锁一起使用时,事务将成为有条件提交.

关于乐观锁,需要注意的是:

  •  WATCH命令必须在MULTI命令之前执行. WATCH命令可以执行多次.
  •  WATCH命令可以指定乐观锁的多个key,如果在事务过程中,任何一个key被其他客户端改变,则当前客户端的乐观锁失败,事务提交时,将丢弃所有命令序列.
  •  多个客户端的WATCH命令可以指定相同的key.

WATCH命令指定乐观锁后,可以接着执行MULTI命令进入事务上下文,也可以在WATCH命令和MULTI命令之间执行其他命令. 具体使用方式取决于场景需求,不在事务中的命令将立即被执行.

如果WATCH命令指定的乐观锁的key,被当前客户端改变,在事务提交时,乐观锁不会失败.

如果WATCH命令指定的乐观锁的key具有超时属性,并且该key在WATCH命令执行后, 在事务提交命令EXEC执行前超时, 则乐观锁不会失败.如果该key被其他客户端对象修改,则乐观锁失败.

一个执行乐观锁机制的事务例子: 

  1. rpush list v1 v2 v3  
  2. :3  
  3. watch list  
  4. +OK  
  5. multi  
  6. +OK 
  7. lpop list  
  8. +QUEUED  
  9. exec  
  10. *1  
  11. $2  
  12. v1 

下面是另一个例子,乐观锁被当前客户端改变, 事务提交成功: 

  1. watch num  
  2. +OK  
  3. multi  
  4. +OK  
  5. incr num  
  6. +QUEUED  
  7. exec  
  8. *1  
  9. :2 

Redis事务和乐观锁配合使用时, 可以构造实现单个Redis命令不能完成的更复杂的逻辑.

Redis事务的源码实现机制

首先,事务开始的MULTI命令执行的函数为multiCommand, 其实现为(multi.c): 

  1. void multiCommand(redisClient *c) {  
  2.     if (c->flags & REDIS_MULTI) {  
  3.         addReplyError(c,"MULTI calls can not be nested");  
  4.         return;  
  5.     }  
  6.     c->flags |= REDIS_MULTI;  
  7.     addReply(c,shared.ok);  

该命令只是在当前客户端对象上加上REDIS_MULTI标志, 表示该客户端进入了事务上下文.

客户端进入事务上下文后,后续执行的命令将被缓存. 函数processCommand是Redis处理客户端命令的入口函数, 其实现为(redis.c): 

  1. int processCommand(redisClient *c) {  
  2.     /* The QUIT command is handled separately. Normal command procs will  
  3.      * go through checking for replication and QUIT will cause trouble  
  4.      * when FORCE_REPLICATION is enabled and would be implemented in  
  5.      * a regular command proc. */  
  6.     if (!strcasecmp(c->argv[0]->ptr,"quit")) {  
  7.         addReply(c,shared.ok); 
  8.          c->flags |= REDIS_CLOSE_AFTER_REPLY;  
  9.         return REDIS_ERR; 
  10.     }  
  11.     /* Now lookup the command and check ASAP about trivial error conditions  
  12.      * such as wrong arity, bad command name and so forth. */  
  13.     c->ccmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);  
  14.     if (!c->cmd) {  
  15.         flagTransaction(c);  
  16.         addReplyErrorFormat(c,"unknown command '%s'",  
  17.             (char*)c->argv[0]->ptr);  
  18.         return REDIS_OK; 
  19.      } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||  
  20.                (c->argc < -c->cmd->arity)) {  
  21.         flagTransaction(c);  
  22.         addReplyErrorFormat(c,"wrong number of arguments for '%s' command",  
  23.             c->cmd->name);  
  24.         return REDIS_OK; 
  25.     }  
  26.     /* Check if the user is authenticated */  
  27.     if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand)  
  28.     {  
  29.         flagTransaction(c);  
  30.         addReply(c,shared.noautherr);  
  31.         return REDIS_OK;  
  32.     }  
  33.     /* Handle the maxmemory directive.  
  34.      *  
  35.      * First we try to free some memory if possible (if there are volatile  
  36.      * keys in the dataset). If there are not the only thing we can do  
  37.      * is returning an error. */  
  38.     if (server.maxmemory) {  
  39.         int retval = freeMemoryIfNeeded();  
  40.         /* freeMemoryIfNeeded may flush slave output buffers. This may result  
  41.          * into a slave, that may be the active client, to be freed. */  
  42.         if (server.current_client == NULL) return REDIS_ERR;  
  43.         /* It was impossible to free enough memory, and the command the client  
  44.          * is trying to execute is denied during OOM conditions? Error. */  
  45.         if ((c->cmd->flags & REDIS_CMD_DENYOOM) && retval == REDIS_ERR) {  
  46.             flagTransaction(c);  
  47.             addReply(c, shared.oomerr);  
  48.             return REDIS_OK;  
  49.         }  
  50.     }  
  51.     /* Don't accept write commands if there are problems persisting on disk  
  52.      * and if this is a master instance. */  
  53.     if (((server.stop_writes_on_bgsave_err &&  
  54.           server.saveparamslen > 0 &&  
  55.           server.lastbgsave_status == REDIS_ERR) ||  
  56.           server.aof_last_write_status == REDIS_ERR) &&  
  57.         server.masterhost == NULL &&  
  58.         (c->cmd->flags & REDIS_CMD_WRITE ||  
  59.          c->cmd->proc == pingCommand)) 
  60.      {  
  61.         flagTransaction(c);  
  62.         if (server.aof_last_write_status == REDIS_OK)  
  63.             addReply(c, shared.bgsaveerr);  
  64.         else  
  65.             addReplySds(c, 
  66.                  sdscatprintf(sdsempty(),  
  67.                 "-MISCONF Errors writing to the AOF file: %s\r\n",  
  68.                 strerror(server.aof_last_write_errno)));  
  69.         return REDIS_OK;  
  70.     }  
  71.     /* Don't accept write commands if there are not enough good slaves and  
  72.      * user configured the min-slaves-to-write option. */  
  73.     if (server.masterhost == NULL &&  
  74.         server.repl_min_slaves_to_write &&  
  75.         server.repl_min_slaves_max_lag && 
  76.          c->cmd->flags & REDIS_CMD_WRITE &&  
  77.         server.repl_good_slaves_count < server.repl_min_slaves_to_write 
  78.     {  
  79.         flagTransaction(c);  
  80.         addReply(c, shared.noreplicaserr);  
  81.         return REDIS_OK;  
  82.     }  
  83.     /* Don't accept write commands if this is a read only slave. But  
  84.      * accept write commands if this is our master. */  
  85.     if (server.masterhost && server.repl_slave_ro &&  
  86.         !(c->flags & REDIS_MASTER) &&  
  87.         c->cmd->flags & REDIS_CMD_WRITE)  
  88.     {  
  89.         addReply(c, shared.roslaveerr);  
  90.         return REDIS_OK;  
  91.     }  
  92.     /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */  
  93.     if (c->flags & REDIS_PUBSUB &&  
  94.         c->cmd->proc != pingCommand &&  
  95.         c->cmd->proc != subscribeCommand &&  
  96.         c->cmd->proc != unsubscribeCommand &&  
  97.         c->cmd->proc != psubscribeCommand &&  
  98.         c->cmd->proc != punsubscribeCommand) {  
  99.         addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");  
  100.         return REDIS_OK;  
  101.     }  
  102.     /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and  
  103.      * we are a slave with a broken link with master. */  
  104.     if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED &&  
  105.         server.repl_serve_stale_data == 0 &&  
  106.         !(c->cmd->flags & REDIS_CMD_STALE))  
  107.     {  
  108.         flagTransaction(c);  
  109.         addReply(c, shared.masterdownerr); 
  110.          return REDIS_OK;  
  111.     }  
  112.     /* Loading DB? Return an error if the command has not the  
  113.      * REDIS_CMD_LOADING flag. */  
  114.     if (server.loading && !(c->cmd->flags & REDIS_CMD_LOADING)) {  
  115.         addReply(c, shared.loadingerr);  
  116.         return REDIS_OK;  
  117.     }  
  118.     /* Lua script too slow? Only allow a limited number of commands. */  
  119.     if (server.lua_timedout &&  
  120.           c->cmd->proc != authCommand &&  
  121.           c->cmd->proc != replconfCommand &&  
  122.         !(c->cmd->proc == shutdownCommand &&  
  123.           c->argc == 2 &&  
  124.           tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&  
  125.         !(c->cmd->proc == scriptCommand &&  
  126.           c->argc == 2 &&  
  127.           tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))  
  128.     {  
  129.         flagTransaction(c);  
  130.         addReply(c, shared.slowscripterr);  
  131.         return REDIS_OK;  
  132.     }  
  133.     /* Exec the command */  
  134.     if (c->flags & REDIS_MULTI &&  
  135.         c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&  
  136.         c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)  
  137.     {  
  138.         queueMultiCommand(c);  
  139.         addReply(c,shared.queued);  
  140.     } else {  
  141.         call(c,REDIS_CALL_FULL);  
  142.         if (listLength(server.ready_keys))  
  143.             handleClientsBlockedOnLists();  
  144.     }  
  145.     return REDIS_OK;  

Line145:151当客户端处于事务上下文时, 如果接收的是非事务命令(MULTI, EXEC, WATCH, DISCARD), 则调用queueMultiCommand将命令缓存起来,然后向客户端发送成功响应.

在函数processCommand中, 在缓存命令之前, 如果检查到客户端发送的命令不存在,或者命令参数个数不正确等情况, 会调用函数flagTransaction标命令缓存失败.也就是说,函数processCommand中, 所有调用函数flagTransaction的条件分支,都是返回失败响应.

缓存命令的函数queueMultiCommand的实现为(multi.c): 

  1. /* Add a new command into the MULTI commands queue */  
  2. void queueMultiCommand(redisClient *c) {  
  3.     multiCmd *mc;  
  4.     int j;  
  5.     c->mstate.commands = zrealloc(c->mstate.commands,  
  6.             sizeof(multiCmd)*(c->mstate.count+1));  
  7.     mc = c->mstate.commands+c->mstate.count;  
  8.     mc->ccmd = c->cmd;  
  9.     mc->argc = c->argc;  
  10.     mc->argv = zmalloc(sizeof(robj*)*c->argc);  
  11.     memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);  
  12.     for (j = 0; j < c->argc; j++)  
  13.         incrRefCount(mc->argv[j]);  
  14.     c->mstate.count++;  

在事务上下文中, 使用multiCmd结构来缓存命令, 该结构定义为(redis.h): 

  1. /* Client MULTI/EXEC state */  
  2. typedef struct multiCmd {  
  3.     robj **argv;  
  4.     int argc;  
  5.     struct redisCommand *cmd;  
  6. } multiCmd; 

其中argv字段指向命令的参数内存地址,argc为命令参数个数, cmd为命令描述结构, 包括名字和函数指针等.

命令参数的内存空间已经使用动态分配记录于客户端对象的argv字段了, multiCmd结构的argv字段指向客户端对象redisClient的argv即可.

无法缓存命令时, 调用函数flagTransaction,该函数的实现为(multi.c): 

  1. /* Flag the transacation as DIRTY_EXEC so that EXEC will fail.  
  2.  * Should be called every time there is an error while queueing a command. */  
  3. void flagTransaction(redisClient *c) {  
  4.     if (c->flags & REDIS_MULTI)  
  5.         c->flags |= REDIS_DIRTY_EXEC;  

该函数在客户端对象中设置REDIS_DIRTY_EXEC标志, 如果设置了这个标志, 事务提交时, 命令序列将被丢弃.

最后,在事务提交时, 函数processCommand中将调用call(c,REDIS_CALL_FULL);, 其实现为(redis.c): 

  1. /* Call() is the core of Redis execution of a command */  
  2. void call(redisClient *c, int flags) { 
  3.      long long dirty, start, duration;  
  4.     int cclient_old_flags = c->flags;  
  5.     /* Sent the command to clients in MONITOR mode, only if the commands are  
  6.      * not generated from reading an AOF. */  
  7.     if (listLength(server.monitors) && 
  8.          !server.loading &&  
  9.         !(c->cmd->flags & (REDIS_CMD_SKIP_MONITOR|REDIS_CMD_ADMIN)))  
  10.     {  
  11.         replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); 
  12.     }  
  13.     /* Call the command. */  
  14.     c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL);  
  15.     redisOpArrayInit(&server.also_propagate);  
  16.     dirty = server.dirty;  
  17.     start = ustime();  
  18.     c->cmd->proc(c);  
  19.     duration = ustime()-start;  
  20.     dirty = server.dirty-dirty;  
  21.     if (dirty < 0dirty = 0 
  22.     /* When EVAL is called loading the AOF we don't want commands called  
  23.      * from Lua to go into the slowlog or to populate statistics. */  
  24.     if (server.loading && c->flags & REDIS_LUA_CLIENT)  
  25.         flags &= ~(REDIS_CALL_SLOWLOG | REDIS_CALL_STATS);  
  26.     /* If the caller is Lua, we want to force the EVAL caller to propagate  
  27.      * the script if the command flag or client flag are forcing the  
  28.      * propagation. */  
  29.     if (c->flags & REDIS_LUA_CLIENT && server.lua_caller) {  
  30.         if (c->flags & REDIS_FORCE_REPL)  
  31.             server.lua_caller->flags |= REDIS_FORCE_REPL;  
  32.         if (c->flags & REDIS_FORCE_AOF)  
  33.             server.lua_caller->flags |= REDIS_FORCE_AOF; 
  34.      } 
  35.     /* Log the command into the Slow log if needed, and populate the  
  36.      * per-command statistics that we show in INFO commandstats. */  
  37.     if (flags & REDIS_CALL_SLOWLOG && c->cmd->proc != execCommand) {  
  38.         char *latency_event = (c->cmd->flags & REDIS_CMD_FAST) ?  
  39.                               "fast-command" : "command";  
  40.         latencyAddSampleIfNeeded(latency_event,duration/1000);  
  41.         slowlogPushEntryIfNeeded(c->argv,c->argc,duration);  
  42.     } 
  43.      if (flags & REDIS_CALL_STATS) {  
  44.         c->cmd->microseconds += duration;  
  45.         c->cmd->calls++;  
  46.     }  
  47.     /* Propagate the command into the AOF and replication link */  
  48.     if (flags & REDIS_CALL_PROPAGATE) {  
  49.         int flags = REDIS_PROPAGATE_NONE 
  50.         if (c->flags & REDIS_FORCE_REPL) flags |= REDIS_PROPAGATE_REPL;  
  51.         if (c->flags & REDIS_FORCE_AOF) flags |= REDIS_PROPAGATE_AOF;  
  52.         if (dirty)  
  53.             flags |= (REDIS_PROPAGATE_REPL | REDIS_PROPAGATE_AOF);  
  54.         if (flags != REDIS_PROPAGATE_NONE)  
  55.             propagate(c->cmd,c->db->id,c->argv,c->argc,flags);  
  56.     }  
  57.     /* Restore the old FORCE_AOF/REPL flags, since call can be executed  
  58.      * recursively. */  
  59.     c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL);  
  60.     c->flags |= client_old_flags & (REDIS_FORCE_AOF|REDIS_FORCE_REPL);  
  61.     /* Handle the alsoPropagate() API to handle commands that want to propagate  
  62.      * multiple separated commands. */  
  63.     if (server.also_propagate.numops) {  
  64.         int j;  
  65.         redisOp *rop;  
  66.         for (j = 0; j < server.also_propagate.numops; j++) {  
  67.             rop = &server.also_propagate.ops[j];  
  68.             propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, rop->target);  
  69.         }  
  70.         redisOpArrayFree(&server.also_propagate);  
  71.     }  
  72.     server.stat_numcommands++;  

在函数call中通过执行c->cmd->proc(c);调用具体的命令函数.事务提交命令EXEC对应的执行函数为execCommand, 其实现为(multi.c): 

  1. void execCommand(redisClient *c) {  
  2.     int j;  
  3.     robj **orig_argv; 
  4.      int orig_argc;  
  5.     struct redisCommand *orig_cmd;  
  6.     int must_propagate = 0; /* Need to propagate MULTI/EXEC to AOF / slaves? */  
  7.     if (!(c->flags & REDIS_MULTI)) {  
  8.         addReplyError(c,"EXEC without MULTI");  
  9.         return;  
  10.     }  
  11.     /* Check if we need to abort the EXEC because:  
  12.      * 1) Some WATCHed key was touched.  
  13.      * 2) There was a previous error while queueing commands.  
  14.      * A failed EXEC in the first case returns a multi bulk nil object  
  15.      * (technically it is not an error but a special behavior), while  
  16.      * in the second an EXECABORT error is returned. */  
  17.     if (c->flags & (REDIS_DIRTY_CAS|REDIS_DIRTY_EXEC)) {  
  18.         addReply(c, c->flags & REDIS_DIRTY_EXEC ? shared.execaborterr :  
  19.                                                   shared.nullmultibulk);  
  20.         discardTransaction(c);  
  21.         goto handle_monitor;  
  22.     }  
  23.     /* Exec all the queued commands */  
  24.     unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */  
  25.     orig_argv = c->argv;  
  26.     orig_argc = c->argc;  
  27.     orig_cmd = c->cmd;  
  28.     addReplyMultiBulkLen(c,c->mstate.count);  
  29.     for (j = 0; j < c->mstate.count; j++) {  
  30.         c->argc = c->mstate.commands[j].argc;  
  31.         c->argv = c->mstate.commands[j].argv;  
  32.         c->ccmd = c->mstate.commands[j].cmd;  
  33.         /* Propagate a MULTI request once we encounter the first write op.  
  34.          * This way we'll deliver the MULTI/..../EXEC block as a whole and  
  35.          * both the AOF and the replication link will have the same consistency  
  36.          * and atomicity guarantees. */  
  37.         if (!must_propagate && !(c->cmd->flags & REDIS_CMD_READONLY)) {  
  38.             execCommandPropagateMulti(c);  
  39.             must_propagate = 1 
  40.         }  
  41.         call(c,REDIS_CALL_FULL);  
  42.         /* Commands may alter argc/argv, restore mstate. */  
  43.         c->mstate.commands[j].argc = c->argc;  
  44.         c->mstate.commands[j].argv = c->argv;  
  45.         c->mstate.commands[j].cmd = c->cmd;  
  46.     }  
  47.     c->argv = orig_argv 
  48.     c->argc = orig_argc 
  49.     c->cmd = orig_cmd 
  50.     discardTransaction(c);  
  51.     /* Make sure the EXEC command will be propagated as well if MULTI  
  52.      * was already propagated. */ 
  53.      if (must_propagate) server.dirty++; 
  54. handle_monitor:  
  55.     /* Send EXEC to clients waiting data from MONITOR. We do it here  
  56.      * since the natural order of commands execution is actually:  
  57.      * MUTLI, EXEC, ... commands inside transaction ... 
  58.       * Instead EXEC is flagged as REDIS_CMD_SKIP_MONITOR in the command  
  59.      * table, and we do it here with correct ordering. */  
  60.     if (listLength(server.monitors) && !server.loading)  
  61.         replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);  

LINE8:11检查EXEC命令和MULTI命令是否配对使用, 单独执行EXEC命令是没有意义的.

LINE19:24检查客户端对象是否具有REDIS_DIRTY_CAS或者REDIS_DIRTY_EXEC标志, 如果存在,则调用函数discardTransaction丢弃命令序列, 向客户端返回失败响应.

如果没有检查到任何错误,则先执行unwatchAllKeys(c);取消该客户端上所有的乐观锁key.

LINE32:52依次执行缓存的命令序列,这里有两点需要注意的是:

事务可能需要同步到AOF缓存或者replica备份节点中.如果事务中的命令序列都是读操作, 则没有必要向AOF和replica进行同步.如果事务的命令序列中包含写命令,则MULTI, EXEC和相关的写命令会向AOF和replica进行同步.根据LINE41:44的条件判断,执行execCommandPropagateMulti(c);保证MULTI命令同步, LINE59检查EXEC命令是否需要同步, 即MULTI命令和EXEC命令必须保证配对同步.EXEC命令的同步执行在函数的call中LINE62propagate(c->cmd,c->db->id,c->argv,c->argc,flags);, 具体的写入命令由各自的执行函数负责同步.

这里执行命令序列时, 通过执行call(c,REDIS_CALL_FULL);所以call函数是递归调用.

所以,综上所述, Redis事务其本质就是,以不可中断的方式依次执行缓存的命令序列,将结果保存到内存cache中.

事务提交时, 丢弃命令序列会调用函数discardTransaction, 其实现为(multi.c): 

  1. void discardTransaction(redisClient *c) {  
  2.     freeClientMultiState(c); 
  3.      initClientMultiState(c);  
  4.     c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS|REDIS_DIRTY_EXEC);  
  5.     unwatchAllKeys(c); 
  6.  

该函数调用freeClientMultiState释放multiCmd对象内存.调用initClientMultiState复位客户端对象的缓存命令管理结构.调用unwatchAllKeys取消该客户端的乐观锁.

WATCH命令执行乐观锁, 其对应的执行函数为watchCommand, 其实现为(multi.c): 

  1. void watchCommand(redisClient *c) {  
  2.     int j;  
  3.     if (c->flags & REDIS_MULTI) {  
  4.         addReplyError(c,"WATCH inside MULTI is not allowed");  
  5.         return;  
  6.     }  
  7.     for (j = 1; j < c->argc; j++)  
  8.         watchForKey(c,c->argv[j]);  
  9.     addReply(c,shared.ok);  

进而调用函数watchForKey, 其实现为(multi.c): 

  1. /* Watch for the specified key */  
  2. void watchForKey(redisClient *c, robj *key) {  
  3.     list *clients = NULL 
  4.     listIter li;  
  5.     listNode *ln;  
  6.     watchedKey *wk;  
  7.     /* Check if we are already watching for this key */  
  8.     listRewind(c->watched_keys,&li);  
  9.     while((ln = listNext(&li))) {  
  10.         wk = listNodeValue(ln);  
  11.         if (wk->db == c->db && equalStringObjects(key,wk->key))  
  12.             return; /* Key already watched */  
  13.     }  
  14.     /* This key is not already watched in this DB. Let's add it */  
  15.     clients = dictFetchValue(c->db->watched_keys,key);  
  16.     if (!clients) {  
  17.         clients = listCreate();  
  18.         dictAdd(c->db->watched_keys,key,clients);  
  19.         incrRefCount(key);  
  20.     }  
  21.     listAddNodeTail(clients,c);  
  22.     /* Add the new key to the list of keys watched by this client */  
  23.     wk = zmalloc(sizeof(*wk));  
  24.     wk->keykey = key;  
  25.     wk->db = c->db;  
  26.     incrRefCount(key);  
  27.     listAddNodeTail(c->watched_keys,wk);  

关于乐观锁的key, 既保存于其客户端对象的watched_keys链表中, 也保存于全局数据库对象的watched_keys哈希表中.

LINE10:14检查客户端对象的链表中是否已经存在该key, 如果已经存在, 则直接返回.LINE16在全局数据库中返回该key对应的客户端对象链表, 如果链表不存在, 说明其他客户端没有使用该key作为乐观锁, 如果链表存在, 说明其他客户端已经使用该key作为乐观锁. LINE22将当前客户端对象记录于该key对应的链表中. LINE28将该key记录于当前客户端的key链表中.

当前客户端执行乐观锁以后, 其他客户端的写入命令可能修改该key值.所有具有写操作属性的命令都会执行函数signalModifiedKey, 其实现为(db.c): 

  1. void signalModifiedKey(redisDb *db, robj *key) {  
  2.     touchWatchedKey(db,key);  

函数touchWatchedKey的实现为(multi.c): 

  1. /* "Touch" a key, so that if this key is being WATCHed by some client the  
  2.  * next EXEC will fail. */  
  3. void touchWatchedKey(redisDb *db, robj *key) {  
  4.     list *clients;  
  5.     listIter li;  
  6.     listNode *ln;  
  7.     if (dictSize(db->watched_keys) == 0) return;  
  8.     clients = dictFetchValue(db->watched_keys, key);  
  9.     if (!clients) return; 
  10.     /* Mark all the clients watching this key as REDIS_DIRTY_CAS */  
  11.     /* Check if we are already watching for this key */  
  12.     listRewind(clients,&li);  
  13.     while((ln = listNext(&li))) {  
  14.         redisClient *c = listNodeValue(ln);  
  15.         c->flags |= REDIS_DIRTY_CAS;  
  16.     }  

语句if (dictSize(db->watched_keys) == 0) return;检查全局数据库中的哈希表watched_keys是否为空, 如果为空,说明没有任何客户端执行WATCH命令, 直接返回.如果该哈希表不为空, 取回该key对应的客户端链表结构,并把该链表中的每个客户端对象设置REDIS_DIRTY_CAS标志. 前面在EXEC的执行命令中,进行过条件判断, 如果客户端对象具有这个标志, 则丢弃事务中的命令序列.

在执行EXEC, DISCARD, UNWATCH命令以及在客户端结束连接的时候,都会取消乐观锁, 最终都会执行函数unwatchAllKeys, 其实现为(multi.c): 

  1. /* Unwatch all the keys watched by this client. To clean the EXEC dirty  
  2.  * flag is up to the caller. */ 
  3.  void unwatchAllKeys(redisClient *c) {  
  4.     listIter li;  
  5.     listNode *ln;  
  6.     if (listLength(c->watched_keys) == 0) return;  
  7.     listRewind(c->watched_keys,&li);  
  8.     while((ln = listNext(&li))) {  
  9.         list *clients;  
  10.         watchedKey *wk;  
  11.         /* Lookup the watched key -> clients list and remove the client  
  12.          * from the list */  
  13.         wk = listNodeValue(ln);  
  14.         clients = dictFetchValue(wk->db->watched_keys, wk->key);  
  15.         redisAssertWithInfo(c,NULL,clients != NULL);  
  16.         listDelNode(clients,listSearchKey(clients,c));  
  17.         /* Kill the entry at all if this was the only client */  
  18.         if (listLength(clients) == 0)  
  19.             dictDelete(wk->db->watched_keys, wk->key);  
  20.         /* Remove this watched key from the client->watched list */  
  21.         listDelNode(c->watched_keys,ln);  
  22.         decrRefCount(wk->key); 
  23.          zfree(wk);  
  24.     }  

语句if (listLength(c->watched_keys) == 0) return;判断如果当前客户端对象的watched_keys链表为空,说明当前客户端没有执行WATCH命令,直接返回.如果该链表非空, 则依次遍历该链表中的key, 并从该链表中删除key, 同时,获得全局数据库中的哈希表watched_keys中该key对应的客户端链表, 删除当前客户端对象. 

 

责任编辑:庞桂玉 来源: 运维派
相关推荐

2021-03-10 10:55:51

SpringJava代码

2022-08-22 08:04:25

Spring事务Atomicity

2018-03-22 18:30:22

数据库MySQL并发控制

2016-12-08 15:36:59

HashMap数据结构hash函数

2020-07-21 08:26:08

SpringSecurity过滤器

2010-06-01 15:25:27

JavaCLASSPATH

2020-03-18 13:40:03

Spring事数据库代码

2023-10-19 11:12:15

Netty代码

2009-09-25 09:14:35

Hibernate日志

2021-02-17 11:25:33

前端JavaScriptthis

2013-09-22 14:57:19

AtWood

2017-01-10 08:48:21

2017-08-15 13:05:58

Serverless架构开发运维

2024-02-21 21:14:20

编程语言开发Golang

2019-06-25 10:32:19

UDP编程通信

2013-08-28 10:11:37

RedisRedis主键失效NoSQL

2014-06-13 11:08:52

Redis主键失效

2023-03-02 08:26:36

RedisAVL红黑树

2014-06-17 10:27:39

Redis缓存

2015-11-04 09:57:18

JavaScript原型
点赞
收藏

51CTO技术栈公众号