• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            阿二的夢(mèng)想船

             

            2011年11月29日

            redis如何刪除過(guò)期數(shù)據(jù)

            隨著nosql風(fēng)潮興起,redis作為當(dāng)中一個(gè)耀眼的明星,也越來(lái)越多的被關(guān)注和使用,我在工作中也廣泛的用到了redis來(lái)充當(dāng)cachekey-value DB,但當(dāng)大家發(fā)現(xiàn)數(shù)據(jù)越來(lái)越多時(shí),不禁有些擔(dān)心,redis能撐的住嗎,雖然官方已經(jīng)有漂亮的benchmark,自己也可以做做壓力測(cè)試,但是看看源碼,也是確認(rèn)問(wèn)題最直接的辦法之一。比如目前我們要確認(rèn)的一個(gè)問(wèn)題是,redis是如何刪除過(guò)期數(shù)據(jù)的?

            用一個(gè)可以"find reference"IDE,沿著setex(Set the value and expiration of a key)命令一窺究竟:

            void setexCommand(redisClient *c) {
                c
            ->argv[3= tryObjectEncoding(c->argv[3]);
                setGenericCommand(c,
            0,c->argv[1],c->argv[3],c->argv[2]);
            }

            setGenericCommand是一個(gè)實(shí)現(xiàn)set,setnx,setex的通用函數(shù),參數(shù)設(shè)置不同而已。

            void setCommand(redisClient *c) {
                c
            ->argv[2= tryObjectEncoding(c->argv[2]);
                setGenericCommand(c,
            0,c->argv[1],c->argv[2],NULL);
            }
             
            void setnxCommand(redisClient *c) {
                c
            ->argv[2= tryObjectEncoding(c->argv[2]);
                setGenericCommand(c,
            1,c->argv[1],c->argv[2],NULL);
            }
             
            void setexCommand(redisClient *c) {
                c
            ->argv[3= tryObjectEncoding(c->argv[3]);
                setGenericCommand(c,
            0,c->argv[1],c->argv[3],c->argv[2]);
            }

            再看setGenericCommand

             1 void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
             2     long seconds = 0/* initialized to avoid an harmness warning */
             3 
             4     if (expire) {
             5         if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
             6             return;
             7         if (seconds <= 0) {
             8             addReplyError(c,"invalid expire time in SETEX");
             9             return;
            10         }
            11     }
            12 
            13     if (lookupKeyWrite(c->db,key) != NULL && nx) {
            14         addReply(c,shared.czero);
            15         return;
            16     }
            17     setKey(c->db,key,val);
            18     server.dirty++;
            19     if (expire) setExpire(c->db,key,time(NULL)+seconds); 
            20     addReply(c, nx ? shared.cone : shared.ok);
            21 }
            22 

            13行處理"Set the value of a key, only if the key does not exist"的場(chǎng)景,17行插入這個(gè)key19行設(shè)置它的超時(shí),注意時(shí)間戳已經(jīng)被設(shè)置成了到期時(shí)間。這里要看一下redisDb(c->db)的定義:

            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 
            *io_keys;              /* Keys with clients waiting for VM I/O */
                dict 
            *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
                
            int id;
            } redisDb;

            僅關(guān)注dictexpires,分別來(lái)存key-value和它的超時(shí),也就是說(shuō)如果一個(gè)key-value是有超時(shí)的,那么它會(huì)存在dict里,同時(shí)也存到expires里,類似這樣的形式:dict[key]:value,expires[key]:timeout.

            當(dāng)然key-value沒(méi)有超時(shí),expires里就不存在這個(gè)key剩下setKeysetExpire兩個(gè)函數(shù)無(wú)非是插數(shù)據(jù)到兩個(gè)字典里,這里不再詳述。


            那么redis是如何刪除過(guò)期key的呢。

            通過(guò)查看dbDelete的調(diào)用者,首先注意到這一個(gè)函數(shù),是用來(lái)刪除過(guò)期key的。

             1 int expireIfNeeded(redisDb *db, robj *key) {
             2     time_t when = getExpire(db,key);
             3 
             4     if (when < 0return 0/* No expire for this key */
             5 
             6     /* Don't expire anything while loading. It will be done later. */
             7     if (server.loading) return 0;
             8 
             9     /* If we are running in the context of a slave, return ASAP:
            10      * the slave key expiration is controlled by the master that will
            11      * send us synthesized DEL operations for expired keys.
            12      *
            13      * Still we try to return the right information to the caller, 
            14      * that is, 0 if we think the key should be still valid, 1 if
            15      * we think the key is expired at this time. */
            16     if (server.masterhost != NULL) {
            17         return time(NULL) > when;
            18     }
            19 
            20     /* Return when this key has not expired */
            21     if (time(NULL) <= when) return 0;
            22 
            23     /* Delete the key */
            24     server.stat_expiredkeys++;
            25     propagateExpire(db,key);
            26     return dbDelete(db,key);
            27 }
            28 

            ifNeed表示能刪則刪,所以4行沒(méi)有設(shè)置超時(shí)不刪,7行在"loading"時(shí)不刪,16行非主庫(kù)不刪,21行未到期不刪。25行同步從庫(kù)和文件。

            再看看哪些函數(shù)調(diào)用了expireIfNeeded,有lookupKeyReadlookupKeyWritedbRandomKeyexistsCommandkeysCommand。通過(guò)這些函數(shù)命名可以看出,只要訪問(wèn)了某一個(gè)key,順帶做的事情就是嘗試查看過(guò)期并刪除,這就保證了用戶不可能訪問(wèn)到過(guò)期的key。但是如果有大量的key過(guò)期,并且沒(méi)有被訪問(wèn)到,那么就浪費(fèi)了許多內(nèi)存。Redis是如何處理這個(gè)問(wèn)題的呢。


            dbDelete的調(diào)用者里還發(fā)現(xiàn)這樣一個(gè)函數(shù):

             1 /* Try to expire a few timed out keys. The algorithm used is adaptive and
             2  * will use few CPU cycles if there are few expiring keys, otherwise
             3  * it will get more aggressive to avoid that too much memory is used by
             4  * keys that can be removed from the keyspace. */
             5 void activeExpireCycle(void) {
             6     int j;
             7 
             8     for (j = 0; j < server.dbnum; j++) {
             9         int expired;
            10         redisDb *db = server.db+j;
            11 
            12         /* Continue to expire if at the end of the cycle more than 25%
            13          * of the keys were expired. */
            14         do {
            15             long num = dictSize(db->expires);
            16             time_t now = time(NULL);
            17 
            18             expired = 0;
            19             if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
            20                 num = REDIS_EXPIRELOOKUPS_PER_CRON;
            21             while (num--) {
            22                 dictEntry *de;
            23                 time_t t;
            24 
            25                 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
            26                 t = (time_t) dictGetEntryVal(de);
            27                 if (now > t) {
            28                     sds key = dictGetEntryKey(de);
            29                     robj *keyobj = createStringObject(key,sdslen(key));
            30 
            31                     propagateExpire(db,keyobj);
            32                     dbDelete(db,keyobj);
            33                     decrRefCount(keyobj);
            34                     expired++;
            35                     server.stat_expiredkeys++;
            36                 }
            37             }
            38         } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
            39     }
            40 }
            41 

            這個(gè)函數(shù)的意圖已經(jīng)有說(shuō)明:刪一點(diǎn)點(diǎn)過(guò)期key,如果過(guò)期key較少,那也只用一點(diǎn)點(diǎn)cpu25行隨機(jī)取一個(gè)key38行刪key成功的概率較低就退出。這個(gè)函數(shù)被放在一個(gè)cron里,每毫秒被調(diào)用一次。這個(gè)算法保證每次會(huì)刪除一定比例的key,但是如果key總量很大,而這個(gè)比例控制的太大,就需要更多次的循環(huán),浪費(fèi)cpu,控制的太小,過(guò)期的key就會(huì)變多,浪費(fèi)內(nèi)存——這就是時(shí)空權(quán)衡了。

             

            最后在dbDelete的調(diào)用者里還發(fā)現(xiàn)這樣一個(gè)函數(shù):

            /* This function gets called when 'maxmemory' is set on the config file to limit
             * the max memory used by the server, and we are out of memory.
             * This function will try to, in order:
             *
             * - Free objects from the free list
             * - Try to remove keys with an EXPIRE set
             *
             * It is not possible to free enough memory to reach used-memory < maxmemory
             * the server will start refusing commands that will enlarge even more the
             * memory usage.
             
            */
            void freeMemoryIfNeeded(void)

            這個(gè)函數(shù)太長(zhǎng)就不再詳述了,注釋部分說(shuō)明只有在配置文件中設(shè)置了最大內(nèi)存時(shí)候才會(huì)調(diào)用這個(gè)函數(shù),而設(shè)置這個(gè)參數(shù)的意義是,你把redis當(dāng)做一個(gè)內(nèi)存cache而不是key-value數(shù)據(jù)庫(kù)。


            以上3種刪除過(guò)期key的途徑,第二種定期刪除一定比例的key是主要的刪除途徑,第一種“讀時(shí)刪除”保證過(guò)期key不會(huì)被訪問(wèn)到,第三種是一個(gè)當(dāng)內(nèi)存超出設(shè)定時(shí)的暴力手段。由此也能看出redis設(shè)計(jì)的巧妙之處,

            posted @ 2011-11-29 19:57 阿二 閱讀(14874) | 評(píng)論 (1)編輯 收藏

            2010年9月10日

            Poco::TCPServer框架解析

                 摘要: POCO C++ Libraries提供一套 C++ 的類庫(kù)用以開(kāi)發(fā)基于網(wǎng)絡(luò)的可移植的應(yīng)用程序,功能涉及線程、文件、流,網(wǎng)絡(luò)協(xié)議包括:HTTP、FTP、SMTP 等,還提供 XML 的解析和 SQL 數(shù)據(jù)庫(kù)的訪問(wèn)接口。不僅給我的工作帶來(lái)極大的便利,而且設(shè)計(jì)巧妙,代碼易讀,注釋豐富,也是非常好的學(xué)習(xí)材料。  閱讀全文

            posted @ 2010-09-10 01:05 阿二 閱讀(18850) | 評(píng)論 (13)編輯 收藏

            2008年9月9日

            從海量數(shù)據(jù)中找出中位數(shù)

            題目和基本思路都來(lái)源網(wǎng)上,本人加以整理。

            題目:在一個(gè)文件中有 10G 個(gè)整數(shù),亂序排列,要求找出中位數(shù)。內(nèi)存限制為 2G。只寫(xiě)出思路即可(內(nèi)存限制為 2G的意思就是,可以使用2G的空間來(lái)運(yùn)行程序,而不考慮這臺(tái)機(jī)器上的其他軟件的占用內(nèi)存)。

            關(guān)于中位數(shù):數(shù)據(jù)排序后,位置在最中間的數(shù)值。即將數(shù)據(jù)分成兩部分,一部分大于該數(shù)值,一部分小于該數(shù)值。中位數(shù)的位置:當(dāng)樣本數(shù)為奇數(shù)時(shí),中位數(shù)=(N+1)/2 ; 當(dāng)樣本數(shù)為偶數(shù)時(shí),中位數(shù)為N/2與1+N/2的均值(那么10G個(gè)數(shù)的中位數(shù),就第5G大的數(shù)與第5G+1大的數(shù)的均值了)。

            分析:明顯是一道工程性很強(qiáng)的題目,和一般的查找中位數(shù)的題目有幾點(diǎn)不同。
            1. 原數(shù)據(jù)不能讀進(jìn)內(nèi)存,不然可以用快速選擇,如果數(shù)的范圍合適的話還可以考慮桶排序或者計(jì)數(shù)排序,但這里假設(shè)是32位整數(shù),仍有4G種取值,需要一個(gè)16G大小的數(shù)組來(lái)計(jì)數(shù)。

            2. 若看成從N個(gè)數(shù)中找出第K大的數(shù),如果K個(gè)數(shù)可以讀進(jìn)內(nèi)存,可以利用最小或最大堆,但這里K=N/2,有5G個(gè)數(shù),仍然不能讀進(jìn)內(nèi)存。

            3. 接上,對(duì)于N個(gè)數(shù)和K個(gè)數(shù)都不能一次讀進(jìn)內(nèi)存的情況,《編程之美》里給出一個(gè)方案:設(shè)k<K,且k個(gè)數(shù)可以完全讀進(jìn)內(nèi)存,那么先構(gòu)建k個(gè)數(shù)的堆,先找出第0到k大的數(shù),再掃描一遍數(shù)組找出第k+1到2k的數(shù),再掃描直到找出第K個(gè)數(shù)。雖然每次時(shí)間大約是nlog(k),但需要掃描ceil(K/k)次,這里要掃描5次。

            解法:首先假設(shè)是32位無(wú)符號(hào)整數(shù)。
            1. 讀一遍10G個(gè)整數(shù),把整數(shù)映射到256M個(gè)區(qū)段中,用一個(gè)64位無(wú)符號(hào)整數(shù)給每個(gè)相應(yīng)區(qū)段記數(shù)。
            說(shuō)明:整數(shù)范圍是0 - 2^32 - 1,一共有4G種取值,映射到256M個(gè)區(qū)段,則每個(gè)區(qū)段有16(4G/256M = 16)種值,每16個(gè)值算一段, 0~15是第1段,16~31是第2段,……2^32-16 ~2^32-1是第256M段。一個(gè)64位無(wú)符號(hào)整數(shù)最大值是0~8G-1,這里先不考慮溢出的情況。總共占用內(nèi)存256M×8B=2GB。

            2. 從前到后對(duì)每一段的計(jì)數(shù)累加,當(dāng)累加的和超過(guò)5G時(shí)停止,找出這個(gè)區(qū)段(即累加停止時(shí)達(dá)到的區(qū)段,也是中位數(shù)所在的區(qū)段)的數(shù)值范圍,設(shè)為[a,a+15],同時(shí)記錄累加到前一個(gè)區(qū)段的總數(shù),設(shè)為m。然后,釋放除這個(gè)區(qū)段占用的內(nèi)存。

            3. 再讀一遍10G個(gè)整數(shù),把在[a,a+15]內(nèi)的每個(gè)值計(jì)數(shù),即有16個(gè)計(jì)數(shù)。

            4. 對(duì)新的計(jì)數(shù)依次累加,每次的和設(shè)為n,當(dāng)m+n的值超過(guò)5G時(shí)停止,此時(shí)的這個(gè)計(jì)數(shù)所對(duì)應(yīng)的數(shù)就是中位數(shù)。

            總結(jié):
            1.以上方法只要讀兩遍整數(shù),對(duì)每個(gè)整數(shù)也只是常數(shù)時(shí)間的操作,總體來(lái)說(shuō)是線性時(shí)間。

            2. 考慮其他情況。
            若是有符號(hào)的整數(shù),只需改變映射即可。若是64為整數(shù),則增加每個(gè)區(qū)段的范圍,那么在第二次讀數(shù)時(shí),要考慮更多的計(jì)數(shù)。若過(guò)某個(gè)計(jì)數(shù)溢出,那么可認(rèn)定所在的區(qū)段或代表整數(shù)為所求,這里只需做好相應(yīng)的處理。噢,忘了還要找第5G+1大的數(shù)了,相信有了以上的成果,找到這個(gè)數(shù)也不難了吧。

            3. 時(shí)空權(quán)衡。
            花費(fèi)256個(gè)區(qū)段也許只是恰好配合2GB的內(nèi)存(其實(shí)也不是,呵呵)。可以增大區(qū)段范圍,減少區(qū)段數(shù)目,節(jié)省一些內(nèi)存,雖然增加第二部分的對(duì)單個(gè)數(shù)值的計(jì)數(shù),但第一部分對(duì)每個(gè)區(qū)段的計(jì)數(shù)加快了(總體改變??待測(cè))。

            4. 映射時(shí)盡量用位操作,由于每個(gè)區(qū)段的起點(diǎn)都是2的整數(shù)冪,映射起來(lái)也很方便。

            posted @ 2008-09-09 22:49 阿二 閱讀(6137) | 評(píng)論 (2)編輯 收藏

            基于boost::multi_array的矩陣相乘

            博客第一篇,還望大家多多指點(diǎn)。

            看了半天的boost::multi_array文檔,才發(fā)現(xiàn)可以用shape()[]這個(gè)的東西,來(lái)取某一維的長(zhǎng)度

            而關(guān)于視圖部分,小弟看的一知半解,
            比如,怎么樣把一個(gè)4×4的矩陣分成4個(gè)2×2的矩陣呢
            雖然可以用別的途徑解決,但還是想看下multi_array的視圖操作

            本來(lái)要實(shí)現(xiàn)下Strassen算法的,
            下面是普通的矩陣乘法。

            #include <iostream>
            #include 
            "boost/multi_array.hpp"
            using namespace std;

            typedef boost::multi_array
            <int2> matrix; 

            matrix matrix_multiply(matrix
            & a,matrix& b)
            {
                matrix::index row
            =a.shape()[0];
                matrix::index col
            =b.shape()[1];
                matrix c(boost::extents[row][col]);

                
            for (matrix::index i=0; i!=a.shape()[0]; ++i)
                    
            for (matrix::index j=0; j!=b.shape()[1]; ++j)
                        
            for (matrix::index k=0; k!=a.shape()[1]; ++k)
                            c[i][j]
            +=a[i][k]*b[k][j];

                
            return c;
            }


            void print(const matrix& m)
            {
                
            for (matrix::index i=0; i!=m.shape()[0]; cout<<endl,++i)
                    
            for (matrix::index j=0; j!=m.shape()[1]; ++j)
                            cout
            <<m[i][j]<<" ";    
            }


            int main() {   

                
            int values[] = {   
                    
            012,   
                    
            345    
                }
            ;   
                
            const int values_size = 6;   
                matrix A(boost::extents[
            2][3]);  
                matrix B(boost::extents[
            3][2]); 
                A.assign(values,values 
            + values_size);
                B.assign(values,values 
            + values_size);

                    cout
            <<"matrix A"<<endl;
                    print(A);   
                cout
            <<endl;cout<<"*"<<endl;cout<<"matrix B"<<endl;
                    print(B);   
                cout
            <<endl;cout<<"="<<endl;cout<<"matrix C"<<endl;
                print(matrix_multiply(A,B));
                cout
            <<endl;  

                
            return 0;
            }
             

            posted @ 2008-09-09 20:21 阿二 閱讀(1604) | 評(píng)論 (1)編輯 收藏

            僅列出標(biāo)題  

            導(dǎo)航

            統(tǒng)計(jì)

            常用鏈接

            留言簿

            隨筆分類

            隨筆檔案

            搜索

            最新評(píng)論

            閱讀排行榜

            評(píng)論排行榜

            亚洲AV无码1区2区久久| 99久久中文字幕| 蜜桃麻豆www久久| 国产精品欧美亚洲韩国日本久久| 久久久网中文字幕| 亚洲国产成人久久笫一页| 国产一级做a爰片久久毛片| 久久91精品综合国产首页| 久久综合亚洲鲁鲁五月天| 精品久久久久久亚洲精品| 久久五月精品中文字幕| 青春久久| 久久精品国产亚洲av水果派| 无码人妻少妇久久中文字幕 | 久久丫精品国产亚洲av不卡 | 99久久99久久精品国产| 欧美午夜精品久久久久久浪潮| 亚洲精品无码久久毛片| 久久精品国产精品亚洲精品| 国产一区二区精品久久凹凸 | 亚洲婷婷国产精品电影人久久 | 无码国内精品久久人妻麻豆按摩| 久久久亚洲裙底偷窥综合| 丰满少妇人妻久久久久久| 久久精品成人免费观看97| 亚洲国产精品久久久久久| 麻豆国内精品久久久久久| 浪潮AV色综合久久天堂| 久久99精品免费一区二区| 亚洲色大成网站www久久九| 国产精品久久久久久久人人看| 久久人人爽人人爽人人片av高请| 九九久久精品国产| av色综合久久天堂av色综合在| 国产亚洲成人久久| 97精品依人久久久大香线蕉97 | 一本久久a久久精品vr综合| 91精品国产高清久久久久久io| 中文字幕无码久久人妻| 激情久久久久久久久久| www.久久热|