《redis设计与实现》第四部分 (第19章 事务)

19 事务

  • Redis通过MULTI、EXEC、WATCH等命令来实现事务功能。
  • 基本概念:事务提供了一种将多个命令请求打包,然后一次性按顺序执行多个命令的机制,在事务执行期间,服务器不会中断事务而改去执行其他客户端的命令请求,它会将事务中的所有命令都执行完毕,然后再去处理其他客户端的命令请求。
  • 执行过程:事务首先以MULTI命令为开始,接着将多个命令放入事务当中,最后由EXEC命令将事务提交给服务器执行

19.1 事务的实现

  • 经历三个阶段:事务开始、命令入队、事务执行

19.1.1 事务开始

  • MULTI命令可以将客户端从非事务状态切换到事务状态,通过打开客户端flags属性中的REDIS_MULTI

19.1.2 命令入队

  • 客户端处于非事务状态,客户端发送的命令会立即被服务器执行
  • 客户端处于事务状态,服务器会根据这个客户端发来的不同命令执行不同的操作
    • 命令:EXEC、DISCARD、WATCH、MULTI四个命令中的其中一个,服务器会立即执行这个命令
    • 命令:EXEC、DISCARD、WATCH、MULTI四个命令以外的命令,服务器并不立即执行这个命令,而是将这个命令放入一个事务队列中,然后向客户端返回QUEUED回复
  • 事务队列是先进先出的方式保存入队命令FIFO
//code0: server.h
typedef struct client {
    // ...
    multiState mstate;      /* MULTI/EXEC state */
    // ...
}
/* Client MULTI/EXEC state */
typedef struct multiCmd {
    robj **argv;
    int argc;
    struct redisCommand *cmd;
} multiCmd;

typedef struct multiState {
    multiCmd *commands;     /* Array of MULTI commands */
    int count;              /* Total number of MULTI commands */
    int cmd_flags;          /* The accumulated command flags OR-ed together.
                               So if at least a command has a given flag, it
                               will be set in this field. */
    int cmd_inv_flags;      /* Same as cmd_flags, OR-ing the ~flags. so that it
                               is possible to know if all the commands have a
                               certain flag. */
    int minreplicas;        /* MINREPLICAS for synchronous replication */
    time_t minreplicas_timeout; /* MINREPLICAS timeout as unixtime. */
} multiState;

19.1.3 执行事务

  • 当一个处于事务状态的客户端向服务器发送EXEC命令时,这个命令会立即被服务器执行
  • 服务器会遍历这个客户端的事务队列,执行队列中保存的所有命令,最后将执行所得的结果全部返回给客户端
//code1 multi.c
void discardTransaction(client *c) {
    freeClientMultiState(c);
    initClientMultiState(c);
    c->flags &= ~(CLIENT_MULTI|CLIENT_DIRTY_CAS|CLIENT_DIRTY_EXEC);
    unwatchAllKeys(c);
}

/* Release all the resources associated with MULTI/EXEC state */
void freeClientMultiState(client *c) {
    int j;

    for (j = 0; j < c->mstate.count; j++) {
        int i;
        multiCmd *mc = c->mstate.commands+j;

        for (i = 0; i < mc->argc; i++)
            decrRefCount(mc->argv[i]);
        zfree(mc->argv);
    }
    zfree(c->mstate.commands);
}

void execCommand(client *c) {
    int j;
    robj **orig_argv;
    int orig_argc;
    struct redisCommand *orig_cmd;
    int must_propagate = 0; /* Need to propagate MULTI/EXEC to AOF / slaves? */
    int was_master = server.masterhost == NULL;

    if (!(c->flags & CLIENT_MULTI)) {
        addReplyError(c,"EXEC without MULTI");
        return;
    }

    /* Check if we need to abort the EXEC because:
     * 1) Some WATCHed key was touched.
     * 2) There was a previous error while queueing commands.
     * A failed EXEC in the first case returns a multi bulk nil object
     * (technically it is not an error but a special behavior), while
     * in the second an EXECABORT error is returned. */
    if (c->flags & (CLIENT_DIRTY_CAS|CLIENT_DIRTY_EXEC)) {
        addReply(c, c->flags & CLIENT_DIRTY_EXEC ? shared.execaborterr :
                                                   shared.nullarray[c->resp]);
        discardTransaction(c);
        goto handle_monitor;
    }

    /* Exec all the queued commands */
    unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
    orig_argv = c->argv;
    orig_argc = c->argc;
    orig_cmd = c->cmd;
    addReplyArrayLen(c,c->mstate.count);
    for (j = 0; j < c->mstate.count; j++) {
        c->argc = c->mstate.commands[j].argc;
        c->argv = c->mstate.commands[j].argv;
        c->cmd = c->mstate.commands[j].cmd;

        /* Propagate a MULTI request once we encounter the first command which
         * is not readonly nor an administrative one.
         * This way we'll deliver the MULTI/..../EXEC block as a whole and
         * both the AOF and the replication link will have the same consistency
         * and atomicity guarantees. */
        if (!must_propagate &&
            !server.loading &&
            !(c->cmd->flags & (CMD_READONLY|CMD_ADMIN)))
        {
            execCommandPropagateMulti(c);
            must_propagate = 1;
        }

        int acl_keypos;
        int acl_retval = ACLCheckCommandPerm(c,&acl_keypos);
        if (acl_retval != ACL_OK) {
            addACLLogEntry(c,acl_retval,acl_keypos,NULL);
            addReplyErrorFormat(c,
                "-NOPERM ACLs rules changed between the moment the "
                "transaction was accumulated and the EXEC call. "
                "This command is no longer allowed for the "
                "following reason: %s",
                (acl_retval == ACL_DENIED_CMD) ?
                "no permission to execute the command or subcommand" :
                "no permission to touch the specified keys");
        } else {
            call(c,server.loading ? CMD_CALL_NONE : CMD_CALL_FULL);
        }

        /* Commands may alter argc/argv, restore mstate. */
        c->mstate.commands[j].argc = c->argc;
        c->mstate.commands[j].argv = c->argv;
        c->mstate.commands[j].cmd = c->cmd;
    }
    c->argv = orig_argv;
    c->argc = orig_argc;
    c->cmd = orig_cmd;
    discardTransaction(c);

    /* Make sure the EXEC command will be propagated as well if MULTI
     * was already propagated. */
    if (must_propagate) {
        int is_master = server.masterhost == NULL;
        server.dirty++;
        /* If inside the MULTI/EXEC block this instance was suddenly
         * switched from master to slave (using the SLAVEOF command), the
         * initial MULTI was propagated into the replication backlog, but the
         * rest was not. We need to make sure to at least terminate the
         * backlog with the final EXEC. */
        if (server.repl_backlog && was_master && !is_master) {
            char *execcmd = "*1\r\n$4\r\nEXEC\r\n";
            feedReplicationBacklog(execcmd,strlen(execcmd));
        }
    }

handle_monitor:
    /* Send EXEC to clients waiting data from MONITOR. We do it here
     * since the natural order of commands execution is actually:
     * MUTLI, EXEC, ... commands inside transaction ...
     * Instead EXEC is flagged as CMD_SKIP_MONITOR in the command
     * table, and we do it here with correct ordering. */
    if (listLength(server.monitors) && !server.loading)
        replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);
}

19.2 WATCH命令的作用

  • WATCH命令是一个乐观锁,在EXEC命令执行之前,监视任意数量的数据库键;在EXEC命令执行时,如果被监视的键至少有一个已经被修改过了,服务器将拒绝执行事务,并向客户端返回代表事务执行失败的空回复(nil)

19.2.1 使用WATCH命令监视数据库键

  • 每个Redis数据库都保存着watched_keys字典,这个字典的键是某个被WATCH命令监视的数据库键,字典的值是一个链表,链表中记录所有监视相应数据库键的客户端
//code2 server.h
typedef struct redisDb {
    dict *dict;                 /* The keyspace for this DB */
    dict *expires;              /* Timeout of keys with a timeout set */
    dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP)*/
    dict *ready_keys;           /* Blocked keys that received a PUSH */
    dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
    int id;                     /* Database ID */
    long long avg_ttl;          /* Average TTL, just for stats */
    unsigned long expires_cursor; /* Cursor of the active expire cycle. */
    list *defrag_later;         /* List of key names to attempt to defrag one by one, gradually. */
} redisDb;

19.2.2 监视机制的触发

  • 所有对数据库进行修改的命令,比如SET、SADD、DEL、FLUSHDB、LPUSH执行结束后,会调用multi.c/touchWatchedKey函数对watched_keys进行检查,查看是否有客户端正在监视刚刚被命令修改过的数据库键,如果有,touchWatchedKey函数会将监视被修改键的客户端的REDIS_DIRTY_CAS标识打开,表示该客户端的事务安全性已经被破坏
//code3 multi.c
/* "Touch" a key, so that if this key is being WATCHed by some client the
 * next EXEC will fail. */
void touchWatchedKey(redisDb *db, robj *key) {
    list *clients;
    listIter li;
    listNode *ln;

    if (dictSize(db->watched_keys) == 0) return;
    clients = dictFetchValue(db->watched_keys, key);
    if (!clients) return;

    /* Mark all the clients watching this key as CLIENT_DIRTY_CAS */
    /* Check if we are already watching for this key */
    listRewind(clients,&li);
    while((ln = listNext(&li))) {
        client *c = listNodeValue(ln);

        c->flags |= CLIENT_DIRTY_CAS;
    }
}

19.2.3 判断事务是否安全

  • 服务器收到客户端发来的EXEC命令,服务器会根据这个客户端是否打开CLIENT_DIRTY_CAS标识来决定是否执行事务
    • 如果客户端打开了,拒绝执行
    • 如果没有,服务器执行

19.3 事务的ACID性质

19.3.1 atomicity:原子性

  • 原子性概念:事务队列中的命令要么全部执行,要么一个都不执行
  • 事务回滚:程序或者数据处理错误,将程序或数据恢复到上一次正确状态的行为
  • Redis:不支持事件回滚机制rollback,即使事务队列中的某个命令在执行期间出现了错误,整个事务也会继续执行下去,直到所有事务队列的所有命令都被执行完毕

19.3.2 consistency:一致性

  • 一致性概念:数据库执行事务之前是一致的,在事务执行之后,无论事务是否执行成功,数据库也应该是一致的
    • 一致:数据符合数据库本身的定义和要求,没有包含非法或者无效的错误数据
  • Redis为了保证事务的一致性,做了错误检测和对应的处理
    • 入队错误:如果命令不存在或者格式不正确,redis拒绝执行这个错误
    • 执行错误:命令实际执行时被触发(对数据库键执行了错误类型的操作等)
    • 服务停机:
      • 服务器运行在无持久化的内存模式下,重启之后数据库空白,符合数据库一致性
      • 服务器运行在RDB模式下,可以还原数据库到一致的状态
      • 服务器运行在AOF模式下,服务器可以根据AOF还原到一致的状态

19.3.3 isolation:隔离性

  • 隔离性概念:数据库中有多个事务并发执行,各个事务之间也不会相互影响,而且在并发状态下执行的事务和串行执行的事务产生结果完全相同
  • Redis:单线程执行事务,且在执行事务期间不会对事务进行中断

19.3.4 durability:持久性

  • 耐久性概念:当一个事务执行完毕后,执行这个事务所得的结果已经被保存到永久性存储介质中。即使服务器在事务执行完毕之后停机,执行事务所得的结果也不会丢失。
  • Redis事务的耐久性和Redis使用的持久化模式相关
    • 服务器运行在无持久化的内存模式下,事务不具有耐久性,重启之后数据库空白,包括事务数据在内的所有服务器数据都将丢失
    • 服务器运行在RDB模式下,服务器只有在特定的保存条件被满足时才会执行BGSAVE命令,对数据库进行保存操作,异步执行的BGSAVE不能保证事务数据第一时间被保存在硬盘里面,该RDB持久化模式下的事务也不具有耐久性
    • 服务器运行在AOF模式下,appendfsync选项为always时,程序总会在执行命令之后调用sync函数,将命令数据保存到硬盘里,该配置下的事务就有耐久性
      • 配置选项no-appendfsync-on-rewrite如果打开,即使AOF设置成always,事务也不具备耐久性【因为该选项打开过程中,BGSAVE或者BGREWRITEAOF执行时,服务器会暂停对AOF文件的同步,以减少I/O阻塞】
    • 服务器运行在AOF模式下,appendfsync选项为everysec时,程序会每秒同步一次命令数据到硬盘,停机如果发生在等待同步的那一秒,可能会造成事务数据丢失,该配置下的事务不具备耐久性
    • 服务器运行在AOF模式下,appendfsync选项为no时,程序会等待操作系统决定何时同步一次命令数据到硬盘,停机如果发生在等待同步过程中,可能会造成事务数据丢失,该配置下的事务不具备耐久性
    • 事务执行的最后一条命令设置成SAVE,可保证事务的耐久性【效率太低】
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值