redis源码浅析--七-redisObject对象(下)(内存回收、共享)

环境说明:redis源码版本 5.0.3;我在阅读源码过程做了注释,git地址:https://gitee.com/xiaoangg/redis_annotation
参考书籍:《redis的设计与实现》
文章推荐:
redis源码阅读-一--sds简单动态字符串
redis源码阅读--二-链表
redis源码阅读--三-redis散列表的实现
redis源码浅析--四-redis跳跃表的实现
redis源码浅析--五-整数集合的实现
redis源码浅析--六-压缩列表
redis源码浅析--七-redisObject对象(下)(内存回收、共享)
redis源码浅析--八-数据库的实现
redis源码浅析--九-RDB持久化
redis源码浅析--十-AOF(append only file)持久化
redis源码浅析--十一.事件(上)文件事件
redis源码浅析--十一.事件(下)时间事件
redis源码浅析--十二.单机数据库的实现-客户端
redis源码浅析--十三.单机数据库的实现-服务端 - 时间事件
redis源码浅析--十三.单机数据库的实现-服务端 - redis服务器的初始化
redis源码浅析--十四.多机数据库的实现(一)--新老版本复制功能的区别与实现原理
redis源码浅析--十四.多机数据库的实现(二)--复制的实现SLAVEOF、PSYNY
redis源码浅析--十五.哨兵sentinel的设计与实现
redis源码浅析--十六.cluster集群的设计与实现
redis源码浅析--十七.发布与订阅的实现
redis源码浅析--十八.事务的实现
redis源码浅析--十九.排序的实现
redis源码浅析--二十.BIT MAP的实现
redis源码浅析--二十一.慢查询日志的实现
redis源码浅析--二十二.监视器的实现

一 内存回收

c语言并不具备自动内存回收的功能,所以redis在自己的对象系统构建了一个引用计数(reference counting)
通过这一机制,程序可以跟踪对象的引用计数信息,在适当的时候自动释放对象,并进行内存回收

每个对象的引用计数信息由redisObject中refcount属性记录:

  • 创建一个对象时引用计数值会被初始化为1
  • 当对象被一个新程序使用时,引用计数+1
  • 当对象不在被一个程序使用时,引用计数-1
  • 当对象引用计数值变为0时,对象占用的内存释放

tips:可以使用命令 OBJECT REFOUNR 命令来查看一个键的引用计数的值

二 内存共享

redis在初始化服务时,会创建一万个字符串对象,这些对象包含了0到9999的整数值;
当服务需要用到0到9999的字符串对象时,服务就会使用这些共享对象,而不是创建新的对象;

当redis多个键共享同一个值的对象时,会执行一下两步操作:

  1. 将数据库的键指向一个现有的值对象
  2. 被共享的对象引用计数+1

以tryObjectEncoding(对字符串尝试编码)函数作为入口,可以看到对象共享和引用计数的操作工程:


//尝试对字符串进行编码,以节省空间
/* Try to encode a string object in order to save space */
robj *tryObjectEncoding(robj *o) {
    long value;
    sds s = o->ptr;
    size_t len;

    /* Make sure this is a string object, the only type we encode
     * in this function. Other types use encoded memory efficient
     * representations but are handled by the commands implementing
     * the type. */
    serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);

    /* We try some specialized encoding only for objects that are
     * RAW or EMBSTR encoded, in other words objects that are still
     * in represented by an actually array of chars. */
    if (!sdsEncodedObject(o)) return o;

    //共享对象 不会进行编码
    /* It's not safe to encode shared objects: shared objects can be shared
     * everywhere in the "object space" of Redis and may end in places where
     * they are not handled. We handle them only as values in the keyspace. */
     if (o->refcount > 1) return o;

    /* Check if we can represent this string as a long integer.
     * Note that we are sure that a string larger than 20 chars is not
     * representable as a 32 nor 64 bit integer. */
    //检查字符串时候可以转化成整数;(字符串如果大于20位,64位存不下,所以一定不能转换)
    len = sdslen(s);
    if (len <= 20 && string2l(s,len,&value)) {
    
        /* This object is encodable as a long. Try to use a shared object.
         * Note that we avoid using shared integers when maxmemory is used
         * because every object needs to have a private LRU field for the LRU
         * algorithm to work well. */
        if ((server.maxmemory == 0 ||
            !(server.maxmemory_policy & MAXMEMORY_FLAG_NO_SHARED_INTEGERS)) &&
            value >= 0 &&
            value < OBJ_SHARED_INTEGERS)
        {
            decrRefCount(o);
            incrRefCount(shared.integers[value]);
            return shared.integers[value];
        } else {
            if (o->encoding == OBJ_ENCODING_RAW) sdsfree(o->ptr);
            o->encoding = OBJ_ENCODING_INT;
            o->ptr = (void*) value;
            return o;
        }
    }

    /*
    如果字符串很小 并且 是使用 RAW编码的
    尝试使用 更高效的 EMBSTR编码方式
    */
    /* If the string is small and is still RAW encoded,
     * try the EMBSTR encoding which is more efficient.
     * In this representation the object and the SDS string are allocated
     * in the same chunk of memory to save space and cache misses. */
    if (len <= OBJ_ENCODING_EMBSTR_SIZE_LIMIT) {
        robj *emb;

        if (o->encoding == OBJ_ENCODING_EMBSTR) return o;
        emb = createEmbeddedStringObject(s,sdslen(s)); //创建 EMB 编码的对象
        decrRefCount(o);
        return emb;
    }

    /*
    不能使用 long 和embstr编码方式
    
    */
    /* We can't encode the object...
     *
     * Do the last try, and at least optimize the SDS string inside
     * the string object to require little space, in case there
     * is more than 10% of free space at the end of the SDS string.
     *
     * We do that only for relatively large strings as this branch
     * is only entered if the length of the string is greater than
     * OBJ_ENCODING_EMBSTR_SIZE_LIMIT. */
    if (o->encoding == OBJ_ENCODING_RAW &&
        sdsavail(s) > len/10)
    {
        o->ptr = sdsRemoveFreeSpace(o->ptr);
    }

    /* Return the original object. */
    return o;
}

 

三 对象的空转时长

redisObject结构中还包含来一个lru属性,lru属性记录来对象最后一次被命令程序访问的时间;

当服务器打开来maxmemory选项,并且服务器用于回收内存的算法是volatile-lru或者是allkeys-lru,那么当服务器占用的内存数超过来maxmeory所设的上限,空转时常较高的那部分键将优先释放;

tips;可以使用OBJECT IDLETIME  命令来查看key的空转时常;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值