写点什么

Sentinel 哨兵机制

作者:周杰伦本人
  • 2022 年 9 月 17 日
    韩国
  • 本文字数:1293 字

    阅读完需:约 4 分钟

Sentinel 哨兵机制

哨兵机制是 Redis 实现高可用的解决方案:由一个或多个 Sentinel 实例组成的 Sentinel 系统可以监视任意多个主服务器和从服务器,如果主服务器下线,Sentinel 自动将下线主服务器下的从服务器升级为新的主服务器,替代原理的主服务器继续处理命令请求,等下线的主服务器恢复后设置为新的主服务器的从服务器

启动并初始化 Sentinel

当一个 Sentinel 启动时,需要以下步骤

1. 初始化服务器

Sentinel 本质是一个运行在特殊模式下的 Redis 服务器,启动 Sentinel 第一步就是初始化一个普通 Redis 服务器,普通服务器在初始化时通过载入 RDB 文件或者 AOF 文件来还原数据库状态,但因为 Sentinel 并不使用数据库,所以初始化 Sentinel 并不会载入 RDB 文件或者 AOF 文件

2. 将普通 Redis 服务器使用的代码替换成 Sentinel 专用代码

普通 Redis 常用端口为 6379,Sentinel 常用端口为 26379


Sentinel 服务器命令表:sentinel.c 的 sentinelcmds


struct redisCommand sentinelcmds[] = {    {"ping",pingCommand,1,"",0,NULL,0,0,0,0,0},    {"sentinel",sentinelCommand,-2,"",0,NULL,0,0,0,0,0},    {"subscribe",subscribeCommand,-2,"",0,NULL,0,0,0,0,0},    {"unsubscribe",unsubscribeCommand,-1,"",0,NULL,0,0,0,0,0},    {"psubscribe",psubscribeCommand,-2,"",0,NULL,0,0,0,0,0},    {"punsubscribe",punsubscribeCommand,-1,"",0,NULL,0,0,0,0,0},    {"info",sentinelInfoCommand,-1,"",0,NULL,0,0,0,0,0}};
复制代码


命令表只有 7 个命令,比普通 redis 服务器的命令表要少很多

3. 初始化 Sentinel 状态

服务器初始化 sentinelState 结构,这个结构保存了服务器中所有和 Sentinel 功能有关的状态


/* Main state. */struct sentinelState {    dict *masters;      /* Dictionary of master sentinelRedisInstances.                           Key is the instance name, value is the                           sentinelRedisInstance structure pointer. */    int tilt;           /* Are we in TILT mode? */    int running_scripts;    /* Number of scripts in execution right now. */    mstime_t tilt_start_time;   /* When TITL started. */    mstime_t previous_time;     /* Time last time we ran the time handler. */    list *scripts_queue;    /* Queue of user scripts to execute. */} sentinel;
复制代码

4. 根据给定的配置文件,初始化 Sentinel 的监视主服务器列表。

Sentinel 的 masters 字典记录所有被 Sentinel 监视的主服务器的相关信息,其中字典的键是被监视主服务器的名字,字典的值是被监视主服务器对应的 sentinelRedisInstance 结构。每个 sentinelRedisInstance 结构代表一个被 Sentinel 监视的 Redis 服务器实例


Sentinel 的初始化引发对 masters 字典的初始化,masters 字典的初始是根据被载入的 Sentinel 配置文件来进行的。

5. 创建连向主服务器的网络连接

Sentinel 会创建两个连向主服务器的异步网路连接:一个是命令连接,专门用于向主服务器发送命令,并接收命令回复,一个是订阅连接,用于订阅主服务器的_sentinel_:hello频道


Sentinel 需要与多个实例创建多个网路连接,所以 Sentinel 使用的是异步连接。

发布于: 刚刚阅读数: 5
用户头像

还未添加个人签名 2020.02.29 加入

公众号《盼盼小课堂》,多平台优质博主

评论

发布
暂无评论
Sentinel哨兵机制_9月月更_周杰伦本人_InfoQ写作社区