`

Redis网络监听(3)

 
阅读更多
是介绍Redis网络监听的最后一篇文章,着重分析定时时间处理函数serverCron,这个函数其实已经和网络监听没多大关系了,当时因为其绑定在Redis自定义的事件库的定时事件上,所以放到一起来讲。serverCron的这个函数对Redis的正常运行来说很重要,对于Redis的使用者来说,最重要的就是能够迅速直观地看到Redis的当前的运行状况(keys,sizes,memory等),serverCron就能够使用户得知这些信息,此外,serverCron这个方法定时周期地运行,还承担了AOF Write,VM Swap,BGSAVE,Rehash的操作,使得Redis的运行更加平稳。还是来直接通过代码来分析:
C代码  收藏代码
int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { 
    int j, loops = server.cronloops; 
    REDIS_NOTUSED(eventLoop); 
    REDIS_NOTUSED(id); 
    REDIS_NOTUSED(clientData); 
 
    /* We take a cached value of the unix time in the global state because
     * with virtual memory and aging there is to store the current time
     * in objects at every object access, and accuracy is not needed.
     * To access a global var is faster than calling time(NULL) */ 
    server.unixtime = time(NULL); 
    /* We have just 22 bits per object for LRU information.
     * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
     * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
     *
     * Note that even if this will wrap after 1.5 years it's not a problem,
     * everything will still work but just some object will appear younger
     * to Redis. But for this to happen a given object should never be touched
     * for 1.5 years.
     *
     * Note that you can change the resolution altering the
     * REDIS_LRU_CLOCK_RESOLUTION define.
     */ 
    updateLRUClock(); 
 
    /* We received a SIGTERM, shutting down here in a safe way, as it is
     * not ok doing so inside the signal handler. */ 
    if (server.shutdown_asap) { 
        if (prepareForShutdown() == REDIS_OK) exit(0); 
        redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); 
    } 
 
    /* Show some info about non-empty databases */ 
    for (j = 0; j < server.dbnum; j++) { 
        long long size, used, vkeys; 
 
        size = dictSlots(server.db[j].dict); 
        used = dictSize(server.db[j].dict); 
        vkeys = dictSize(server.db[j].expires); 
        if (!(loops % 50) && (used || vkeys)) { 
            redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); 
            /* dictPrintStats(server.dict); */ 
        } 
    } 
 
    /* We don't want to resize the hash tables while a bacground saving
     * is in progress: the saving child is created using fork() that is
     * implemented with a copy-on-write semantic in most modern systems, so
     * if we resize the HT while there is the saving child at work actually
     * a lot of memory movements in the parent will cause a lot of pages
     * copied. */ 
    if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) { 
        if (!(loops % 10)) tryResizeHashTables(); 
        if (server.activerehashing) incrementallyRehash(); 
    } 
 
    /* Show information about connected clients */ 
    if (!(loops % 50)) { 
        redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", 
            listLength(server.clients)-listLength(server.slaves), 
            listLength(server.slaves), 
            zmalloc_used_memory()); 
    } 
 
    /* Close connections of timedout clients */ 
    if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients) 
        closeTimedoutClients(); 
 
    /* Check if a background saving or AOF rewrite in progress terminated */ 
    if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) { 
        int statloc; 
        pid_t pid; 
 
        if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { 
            if (pid == server.bgsavechildpid) { 
                backgroundSaveDoneHandler(statloc); 
            } else { 
                backgroundRewriteDoneHandler(statloc); 
            } 
            updateDictResizePolicy(); 
        } 
    } else { 
        /* If there is not a background saving in progress check if
         * we have to save now */ 
         time_t now = time(NULL); 
         for (j = 0; j < server.saveparamslen; j++) { 
            struct saveparam *sp = server.saveparams+j; 
 
            if (server.dirty >= sp->changes && 
                now-server.lastsave > sp->seconds) { 
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", 
                    sp->changes, sp->seconds); 
                rdbSaveBackground(server.dbfilename); 
                break; 
            } 
         } 
    } 
 
    /* Expire a few keys per cycle, only if this is a master.
     * On slaves we wait for DEL operations synthesized by the master
     * in order to guarantee a strict consistency. */ 
    if (server.masterhost == NULL) activeExpireCycle(); 
 
    /* Swap a few keys on disk if we are over the memory limit and VM
     * is enbled. Try to free objects from the free list first. */ 
    if (vmCanSwapOut()) { 
        while (server.vm_enabled && zmalloc_used_memory() > 
                server.vm_max_memory) 
        { 
            int retval = (server.vm_max_threads == 0) ? 
                        vmSwapOneObjectBlocking() : 
                        vmSwapOneObjectThreaded(); 
            if (retval == REDIS_ERR && !(loops % 300) && 
                zmalloc_used_memory() > 
                (server.vm_max_memory+server.vm_max_memory/10)) 
            { 
                redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); 
            } 
            /* Note that when using threade I/O we free just one object,
             * because anyway when the I/O thread in charge to swap this
             * object out will finish, the handler of completed jobs
             * will try to swap more objects if we are still out of memory. */ 
            if (retval == REDIS_ERR || server.vm_max_threads > 0) break; 
        } 
    } 
 
    /* Replication cron function -- used to reconnect to master and
     * to detect transfer failures. */ 
    if (!(loops % 10)) replicationCron(); 
 
    server.cronloops++; 
    return 100; 

 
/* This function gets called every time Redis is entering the
* main loop of the event driven library, that is, before to sleep
* for ready file descriptors. */ 
void beforeSleep(struct aeEventLoop *eventLoop) { 
    REDIS_NOTUSED(eventLoop); 
    listNode *ln; 
    redisClient *c; 
 
    /* Awake clients that got all the swapped keys they requested */ 
    if (server.vm_enabled && listLength(server.io_ready_clients)) { 
        listIter li; 
 
        listRewind(server.io_ready_clients,&li); 
        while((ln = listNext(&li))) { 
            c = ln->value; 
            struct redisCommand *cmd; 
 
            /* Resume the client. */ 
            listDelNode(server.io_ready_clients,ln); 
            c->flags &= (~REDIS_IO_WAIT); 
            server.vm_blocked_clients--; 
            aeCreateFileEvent(server.el, c->fd, AE_READABLE, 
                readQueryFromClient, c); 
            cmd = lookupCommand(c->argv[0]->ptr); 
            redisAssert(cmd != NULL); 
            call(c,cmd); 
            resetClient(c); 
            /* There may be more data to process in the input buffer. */ 
            if (c->querybuf && sdslen(c->querybuf) > 0) 
                processInputBuffer(c); 
        } 
    } 
 
    /* Try to process pending commands for clients that were just unblocked. */ 
    while (listLength(server.unblocked_clients)) { 
        ln = listFirst(server.unblocked_clients); 
        redisAssert(ln != NULL); 
        c = ln->value; 
        listDelNode(server.unblocked_clients,ln); 
        c->flags &= ~REDIS_UNBLOCKED; 
 
        /* Process remaining data in the input buffer. */ 
        if (c->querybuf && sdslen(c->querybuf) > 0) 
            processInputBuffer(c); 
    } 
 
    /* Write the AOF buffer on disk */ 
    flushAppendOnlyFile(); 

i.    首先将server.cronloops的值赋给loops,server.cronloops指的是serverCron函数的运行次数,每运行一次serverCron函数,server.cronloops++,server.cronloops的内部执行逻辑随着server.cronloops值的不同而改变;
ii.    用server.unixtime = time(NULL)来保存当前时间,因为在virtual memory and aging的时候,需要知道每次Object的access时间,但是这个时间不需要很精确,所以通过全局变量来获取时间比调用time(NULL)快多了;
iii.    记录Redis的最大内存使用量;如果收到了SIGTERM信号,则试图终止Redis
iv.    serverCron方法每运行50次显示Redis内各个非空的DB的使用情况(used,keys,sizes)及当前连接的clients,使用的内存大小;
v.    serverCron方法每运行10次,将试图进行一次Rehash,如果一个a bacground saving正在进行,则不进行rehash,以免造成部分数据丢失;
vi.    关闭timeout的clients;
vii.    如果在执行BGSAVE期间,client执行了bgrewriteaof这个命令,则在serverCron将开始执行a scheduled AOF rewrite
viii.    如果当前Redis正在进行BGSAVE或者AOF rewrite,则check BGSAVE或者AOF rewrite是否已经终止,如果终止则调用相应的函数处理(backgroundSaveDoneHandler/backgroundRewriteDoneHandler),如果当前没有BGSAVE或者AOF rewrite操作,则判断是否进行此类操作,如果需要,则触发此类操作;
ix.    如果有AOF buffer flush操作被暂停了,则每次调用serverCron的时候,恢复AOF buffer flush操作
x.    如果是Master,则周期性地使某些key(随即挑选的)过期,注意这个操作仅仅只针对Master,如果是slaves,则只有通过master的del操作来同步key,以做到强一致性;
xi.    VM的Swap操作
xii.    每运行10次,进行replicationCron,如果存在slaves的话
xiii.    返回100,表示serverCron方法每100毫秒被调用一次,这一点在processTimeEvent这个方法里得以体现:
C代码  收藏代码
if (retval != AE_NOMORE) { 
                aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); 
            } else { 
                aeDeleteTimeEvent(eventLoop, id); 
            } 
           
通过上面的分析,ServerCron侧重在Rehash,VM Swap, AOF write,BGSAVE等操作,而这些操作都是耗时,而且影响Redis对Clients的响应速度的,因此我们在实际应用的时候可以根据具体情况通过改变类似这样的操作:”loops % 10“来决定上述耗时操作的执行频率,有空我会测试下在不同频率下,redis在压力测试下的性能。

此次, Redis的网络监听部分都介绍完了。再回过头来看前面提到的几个问题:
1.         Redis支持 epoll, select, kquque,,通过配置文件来决定采取哪一种
2.         支持文件读写事件和定时事件
3.         采用数组来维护文件事件,链表来保存定时事件(在查找定时事件时,性能不高,有待提高)
4.         Redis Server单线程响应事件,按照先后顺序来响应事件,因此单台 Redis服务器的吞吐量会随着连接的 clients越来越多而下降,可以通过增加更多的 Redis服务器来解决这个问题
5.         Redis在很多代码里都考虑到了尽快地响应各种事件,如在 aeProcessEvent里面,轮询的 wait时间等于当前时间和最近的定时事件响应时间的差值;每次进入轮询 wait之前,在 beforesleep方法里先响应刚刚 unblock的 clients等。
分享到:
评论

相关推荐

    redis网络层echo例子

    本篇文章将深入探讨Redis网络层的工作原理,并通过一个"echo"测试例子来加深理解。 Redis网络层的核心在于它的事件驱动模型,它基于libevent库来处理来自客户端的连接请求和数据传输。libevent是一个跨平台的事件...

    关于Redis网络模型的源码详析

    在本文中,我们将重点探讨基于epoll的Redis网络模型。 首先,`epoll_create()`系统调用用于创建一个epoll实例,它返回一个专用于epoll的文件描述符。参数表示可以监听的最大socket文件描述符数量。`epoll_ctl()`则...

    Redis集群下过期key监听的实现代码

    文章中也提到,目前网络上没有现成的解决方案来完美解决在Redis集群下监听key过期的问题。实现一个高效且准确的过期key监听机制需要对Redis集群的内部原理有深入的理解。 从提供的代码片段中,我们可以看到实现的...

    cent OS7无网络安装redis

    在CentOS 7环境下,没有网络的情况下安装Redis是一项挑战,因为通常我们会依赖在线包管理器如`yum`来获取和安装软件。然而,通过手动下载所需的依赖包并使用本地安装方式,我们仍然可以完成Redis的安装。以下是详细...

    redis+redis-desktop-manager-0.8.3.3850+笔记

    Redis以网络服务的方式运行,允许客户端通过网络连接进行读写操作,广泛应用于缓存、消息队列、实时统计等多种场景。 **Redis的优势** 1. 高性能:Redis是基于内存的操作,读写速度极快。 2. 数据结构丰富:支持...

    linux离线安装redis

    默认情况下,Redis会监听6379端口。如果你需要更改端口,需要编辑`redis.conf`配置文件。找到`bind 127.0.0.1`和`port 6379`这两行,取消`bind`行的注释,并将`port`设置为你希望的端口,例如: ```conf # 绑定所有...

    Redis 服务器

    - **安全策略**:由于Redis默认监听所有网络接口,可能存在安全隐患,建议配置为仅监听特定IP或启用密码认证。 - **资源限制**:根据服务器资源情况调整Redis配置,如最大内存限制、文件描述符数量等。 - **监控与...

    redis集群redis集群

    3. port指令,用于指定Redis监听的端口号。 4. cluster-enabled指令,设置为yes以启用集群模式。 5. cluster-config-file指令,指定集群状态文件的名称。 6. cluster-node-timeout指令,设置集群节点超时时间。 7. ...

    redis linux rpm离线安装.zip

    默认情况下,Redis监听所有网络接口,为提高安全性,建议限制只监听本地环回地址(127.0.0.1)。此外,还可以配置访问密码,防止未经授权的访问。 10. **监控与维护**: 为了确保Redis的稳定运行,定期检查系统...

    redis 配置详细介绍

    默认情况下,Redis会监听所有网络接口,如果你只想让它监听特定的IP,如127.0.0.1,可以设置`bind 127.0.0.1`,这有助于提高安全性。 Redis提供了多种数据持久化方式,包括RDB(快照)和AOF(Append Only File)。...

    windows redis 安装 redis 安装 redis 安装

    - `bind`:指定 Redis 服务监听的 IP 地址,如果不配置或设置为 0.0.0.0,则监听所有网络接口。 - `requirepass`:设置访问密码,增加安全性。 - `appendonly yes/no`:是否开启持久化,如果开启,数据将在每次写...

    redis(window)

    - `bind`: 指定Redis服务器监听的IP地址,默认为本机所有网络接口。 - `protected-mode`: 保护模式,如果设置为`yes`,则只有本地连接可以访问。 - `maxmemory`: 设置Redis的最大内存大小,超过此值会触发LRU...

    redis.conf,版本7.0.8

    默认情况下,Redis会监听所有可用的网络接口。若只想限制在特定IP上,可以在此配置。 3. `daemonize`: 是否以守护进程方式运行Redis。`yes`表示后台运行,`no`表示前台运行,便于调试。 4. `pidfile`: 指定Redis...

    redis mac 7.2.3 arm 包

    - 默认情况下,Redis监听所有网络接口,出于安全原因,建议修改配置文件,仅监听本地接口(`bind 127.0.0.1`)。 - 设置密码认证(`requirepass`),防止未授权访问。 - 避免在生产环境中暴露Redis直接面对互联网...

    redis-windows-7.0.10.zip

    其中,`bind`配置项用于指定Redis服务器监听的网络接口,`port`定义了服务端口,默认为6379;`maxmemory`用于设置Redis的最大内存使用量,超过此值将触发LRU(最近最少使用)或LFU(最不经常使用)的内存淘汰策略。 ...

    redis6.2.5安装包Windows版

    3. 启动Redis:打开命令行,进入Redis安装目录的bin文件夹,输入`redis-server.exe redis.windows.conf`启动Redis服务。 4. 测试连接:在同一目录下,输入`redis-cli.exe`,然后`ping`,如果返回`PONG`,说明Redis已...

    docker redis 3.2 配置文件

    在默认情况下,Redis 会监听 6379 端口。在 Docker 中,通常会通过 `-p` 或 `--publish` 参数将容器内的端口映射到主机的某个端口。如果“端口绑定注销”,可能意味着你希望避免自动映射,而是通过 Docker Compose ...

    redis7.0.5 Windows版本

    同时,根据网络需求,可以调整监听IP地址和端口。 8. **主从复制** Redis 7.0.5支持主从复制,可以创建多个从节点来备份主节点的数据,提高数据可用性和容错能力。在Windows环境下,配置复制同样简单,只需指定主...

    redis 搭建 配置 运行

    - `bind`: 指定Redis服务器监听的IP地址,默认监听所有网络接口。 - `maxclients`: 设置最大客户端连接数,防止资源耗尽。 - `dbfilename`: 定义RDB持久化文件名。 - `dir`: 指定数据文件的存储目录。 3. **...

    redis解压版最新

    - Redis通过网络协议与客户端交互,支持多种编程语言的客户端库。 2. **Windows下的Redis配置**: - `redis.windows-service.conf` 和 `redis.windows.conf` 是Redis在Windows上的配置文件。 - `redis.windows-...

Global site tag (gtag.js) - Google Analytics