美文网首页
Redis笔记之单机数据库

Redis笔记之单机数据库

作者: slxixiha | 来源:发表于2021-09-04 14:33 被阅读0次

    服务器的数据库

    Redis服务器将所有数据库都保存在服务器状态redisServer的结构中:

    // redis.h
    struct redisServer {
        /* General */
        // ...
        redisDb *db;
        // ...
        int dbnum;                      /* Total number of configured DBs */
        // ...
    };
    

    db:指向redisDb数组的指针,也就是实际的数据库;

    dbnum:数据库的个数,由数据库选项--dbnum决定,默认是16个;

    单个数据库的定义

    /* Redis database representation. There are multiple databases identified
     * by integers from 0 (the default database) up to the max configured
     * database. The database number is the 'id' field in the structure. */
    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;
    

    切换数据库

    每个redis client同时只能访问一个数据库,默认选择的是0号数据库。

    // networking.c
    client *createClient(connection *conn) {
        client *c = zmalloc(sizeof(client));
    
        // ...
    
        selectDb(c,0);
    
        // ...
    }
    

    可以通过select命令选择目标数据库。

    127.0.0.1:6379> set msg "hello world"
    OK
    127.0.0.1:6379> get msg
    "hello world"
    127.0.0.1:6379> select 1
    OK
    127.0.0.1:6379[1]> get msg
    (nil)
    127.0.0.1:6379[1]> set msg "db index 1"
    OK
    127.0.0.1:6379[1]> get msg
    "db index 1"
    127.0.0.1:6379[1]> select 0
    OK
    127.0.0.1:6379> get msg
    "hello world"
    

    关于切换数据细节见以下代码:

    // db.c
    int selectDb(client *c, int id) {
        if (id < 0 || id >= server.dbnum)
            return C_ERR;C
        c->db = &server.db[id];
        return C_OK;
    }
    

    从这里可以看出,所谓的切换数据库其实就是把对应数据库的指针赋值给redis client的指针。这个方式只能在单机的时候。

    相关文章

      网友评论

          本文标题:Redis笔记之单机数据库

          本文链接:https://www.haomeiwen.com/subject/uderwltx.html