zoukankan      html  css  js  c++  java
  • node-cache

    From: https://www.npmjs.com/package/node-cache

    Simple and fast NodeJS internal caching.

    A simple caching module that has setget and delete methods and works a little bit like memcached. Keys can have a timeout (ttl) after which they expire and are deleted from the cache. All keys are stored in a single object so the practical limit is at around 1m keys.

    Since 4.1.0Key-validation: The keys can be given as either string or number, but are casted to a string internally anyway. All other types will either throw an error or call the callback with an error.

    Install

      npm install node-cache --save

    Or just require the node_cache.js file to get the superclass

    Examples:

    Initialize (INIT):

    const NodeCache require"node-cache);
    const myCache new NodeCache();

    Options

    • stdTTL(default: 0) the standard ttl as number in seconds for every generated cache element. 0 = unlimited
    • checkperiod(default: 600) The period in seconds, as a number, used for the automatic delete check interval. 0 = no periodic check.
    • errorOnMissing(default: false) en/disable throwing or passing an error to the callback if attempting to .get a missing or expired value.
    • useClones(default: true) en/disable cloning of variables. If true you'll get a copy of the cached variable. If false you'll save and get just the reference. Note: true is recommended, because it'll behave like a server-based caching. You should set false if you want to save mutable objects or other complex types with mutability involved and wanted. Here's a simple code exmaple showing the different behavior
    • deleteOnExpire(default: true) whether variables will be deleted automatically when they expire. If true the variable will be deleted. If false the variable will remain. You are encouraged to handle the variable upon the event expired by yourself.
    const NodeCache require"node-cache);
    const myCache new NodeCache{ stdTTL100, checkperiod120 );

    Store a key (SET):

    myCache.set( key, val, [ ttl ], [callback] )

    Sets a key value pair. It is possible to define a ttl (in seconds). Returns true on success.

    obj { my"Special", variable42 };
    myCache.set"myKey", objfunctionerrsuccess ){
      if!err && success ){
        console.log( success );
        // true
        // ... do something ...
      }
    });

    Note: If the key expires based on it's ttl it will be deleted entirely from the internal data object.

    Since 1.0.0: Callback is now optional. You can also use synchronous syntax.

    obj { my"Special", variable42 };
    success myCache.set"myKey", obj10000 );
    // true

    Retrieve a key (GET):

    myCache.get( key, [callback] )

    Gets a saved value from the cache. Returns a undefined if not found or expired. If the value was found it returns an object with the key value pair.

    myCache.get"myKey"functionerrvalue ){
      if!err ){
        if(value == undefined){
          // key not found
        }else{
          console.log( value );
          //{ my: "Special", variable: 42 }
          // ... do something ...
        }
      }
    });

    Since 1.0.0: Callback is now optional. You can also use synchronous syntax.

    value myCache.get"myKey);
    if ( value == undefined ){
      // handle miss!
    }
    // { my: "Special", variable: 42 }

    Since 2.0.0:

    The return format changed to a simple value and a ENOTFOUND error if not found ( as callback( err ) or on sync call as result instance of Error ).

    Since 2.1.0:

    The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error. So after 2.1.0 a miss returns undefined.

    Since 3.1.0 errorOnMissing option added

    try{
        value myCache.get"not-existing-key"true );
    catch( err ){
        // ENOTFOUND: Key `not-existing-key` not found
    }

    Get multiple keys (MGET):

    myCache.mget( [ key1, key2, ... ,keyn ], [callback] )

    Gets multiple saved values from the cache. Returns an empty object {} if not found or expired. If the value was found it returns an object with the key value pair.

    myCache.mget"myKeyA""myKeyB]functionerrvalue ){
      if!err ){
        console.log( value );
        /*
          {
            "myKeyA": { my: "Special", variable: 123 },
            "myKeyB": { the: "Glory", answer: 42 }
          }
        */
        // ... do something ...
      }
    });

    Since 1.0.0: Callback is now optional. You can also use synchronous syntax.

    value myCache.mget"myKeyA""myKeyB);
    /*
      {
        "myKeyA": { my: "Special", variable: 123 },
        "myKeyB": { the: "Glory", answer: 42 }
      }
    */

    Since 2.0.0:

    The method for mget changed from .get( [ "a", "b" ] ) to .mget( [ "a", "b" ] )

    Delete a key (DEL):

    myCache.del( key, [callback] )

    Delete a key. Returns the number of deleted entries. A delete will never fail.

    myCache.del"myKey"functionerrcount ){
      if!err ){
        console.log( count )// 1
        // ... do something ...
      }
    });

    Since 1.0.0: Callback is now optional. You can also use synchronous syntax.

    value myCache.del"A);
    // 1

    Delete multiple keys (MDEL):

    myCache.del( [ key1, key2, ... ,keyn ], [callback] )

    Delete multiple keys. Returns the number of deleted entries. A delete will never fail.

    myCache.del"myKeyA""myKeyB]functionerrcount ){
      if!err ){
        console.log( count )// 2
        // ... do something ...
      }
    });

    Since 1.0.0: Callback is now optional. You can also use synchronous syntax.

    value myCache.del"A);
    // 1
     
    value myCache.del"B""C);
    // 2
     
    value myCache.del"A""B""C""D);
    // 1 - because A, B and C not exists

    Change TTL (TTL):

    myCache.ttl( key, ttl, [callback] )

    Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.

    The key will be deleted when passing in a ttl < 0.

    myCache new NodeCache{ stdTTL100 )
    myCache.ttl"existendKey"100functionerrchanged ){
      if!err ){
        console.log( changed )// true
        // ... do something ...
      }
    });
     
    myCache.ttl"missingKey"100functionerrchanged ){
      if!err ){
        console.log( changed )// false
        // ... do something ...
      }
    });
     
    myCache.ttl"existendKey"functionerrchanged ){
      if!err ){
        console.log( changed )// true
        // ... do something ...
      }
    });

    Get TTL (getTTL):

    myCache.getTtl( key, [callback] )

    Receive the ttl of a key. You will get:

    • undefined if the key does not exist
    • 0 if this key has no ttl
    • a timestamp in ms until the key expires
    myCache new NodeCache{ stdTTL100 )
     
    // Date.now() = 1456000500000
    myCache.set"ttlKey""MyExpireData)
    myCache.set"noTtlKey""NonExpireData")
     
    ts myCache.getTtl"ttlKey)
    // ts wil be approximately 1456000600000
     
    myCache.getTtl"ttlKey"functionerrts ){
      if!err ){
        // ts wil be approximately 1456000600000
      }
    });
    // ts wil be approximately 1456000600000
     
    ts myCache.getTtl"noTtlKey)
    // ts = 0
     
    ts myCache.getTtl"unknownKey)
    // ts = undefined
     

    List keys (KEYS)

    myCache.keys( [callback] )

    Returns an array of all existing keys.

    // async
    myCache.keysfunctionerrmykeys ){
      if!err ){
        console.log( mykeys );
       // [ "all", "my", "keys", "foo", "bar" ]
      }
    });
     
    // sync
    mykeys myCache.keys();
     
    console.log( mykeys );
    // [ "all", "my", "keys", "foo", "bar" ]
     

    Statistics (STATS):

    myCache.getStats()

    Returns the statistics.

    myCache.getStats();
      /*
        {
          keys: 0,    // global key count
          hits: 0,    // global hit count
          misses: 0,  // global miss count
          ksize: 0,   // global key size count
          vsize: 0    // global value size count
        }
      */

    Flush all data (FLUSH):

    myCache.flushAll()

    Flush all data.

    myCache.flushAll();
    myCache.getStats();
      /*
        {
          keys: 0,    // global key count
          hits: 0,    // global hit count
          misses: 0,  // global miss count
          ksize: 0,   // global key size count
          vsize: 0    // global value size count
        }
      */

    Close the cache:

    myCache.close()

    This will clear the interval timeout which is set on check period option.

    myCache.close();

    Events

    set

    Fired when a key has been added or changed. You will get the key and the value as callback argument.

    myCache.on"set"functionkeyvalue ){
      // ... do something ...
    });

    del

    Fired when a key has been removed manually or due to expiry. You will get the key and the deleted value as callback arguments.

    myCache.on"del"functionkeyvalue ){
      // ... do something ...
    });

    expired

    Fired when a key expires. You will get the key and value as callback argument.

    myCache.on"expired"functionkeyvalue ){
      // ... do something ...
    });

    flush

    Fired when the cache has been flushed.

    myCache.on"flush"function(){
      // ... do something ...
    });
  • 相关阅读:
    SpringBoot Actuator
    Mysql中实现row_number
    .添加索引和类型,同时设定edgengram分词和charsplit分词
    mysql临时禁用触发器
    centos6.7下安装mvn 、安装elasticsearch下ik分词
    ElasticSearch 自定义排序处理
    ElasticSearch返回不同的type的序列化
    Elasticsearch判断多列存在、bool条件组合查询示例
    C#多线程环境下调用 HttpWebRequest 并发连接限制
    centos6.7安装Redis
  • 原文地址:https://www.cnblogs.com/time-is-life/p/9396438.html
Copyright © 2011-2022 走看看