Narcoleptic Programmers' Medicine
    Wondering what’s next for npm?Check out our public roadmap! »

    clustered-cache
    TypeScript icon, indicating that this package has built-in type declarations

    1.1.3 • Public • Published

    This package allows you to cache data in clustered enviroment. This is simply done with master-worker messaging which allows to send data between multiple processes. Cache is then created in master process and every other process will automatically create communication interface for sharing data.

    Disclaimer

    • This module will not help you to estabilish clustered enviroment
    • Both master and workers processes will be sending messages (IPC)
    • Race conditions can occur, it is your's responsibily to lock and unlock keys manually

    Usage

    Simple use

    import cluster from 'cluster';
    import { ClusteredCache } from 'clustered-cache';
     
    const MY_KEY = 'ILikeHotDogs';
     
    /* Creating cache in master works the same as in worker.
       All the magic is happening inside automatically. */
    let cache = new ClusteredCache();
     
    if (cluster.isMaster) {
       cache.set(MY_KEY, 'Hello, world!')
          .then(() => cluster.fork());
    } else {
       cache.get<string>(MY_KEY)
          .then((val) => console.log(val)); // Should print "Hello, world!".
    }

    Chained use with locks

    import cluster from 'cluster';
    import { ClusteredCache } from './index';
     
    const CACHE_KEY = 'ILikeHotCats';
    let cache = new ClusteredCache();
     
    if (cluster.isMaster) {
       cache.set(CACHE_KEY, 0)
          .then(() => {
             cluster.fork();
             cluster.fork();
             cluster.fork();
          });
    } else {
       cache.lock(CACHE_KEY)
          .then(() => {
             return cache.get<number>(CACHE_KEY);
          })
          .then((val) => {
             console.log(val);
             return cache.set(CACHE_KEY, ++val);
          })
          .then(() => {
             // Do not forget to unlock key! 
             return cache.unlock(CACHE_KEY);
          });
    }
    /* Should print: 
       0 
       1 
       2
    */

    Current usable functions

    (will be extended lately)

    Get the key value:

    public get<T>(key: string): Promise<T>;

    Set the value of key:

    public set<T>(key: string, value: T): Promise<boolean>;

    Delete key:

    public del(key: string): Promise<boolean>;

    Locks the key:

    public lock(key: string): Promise<void>;

    Unlocks the key:

    public unlock(key: string): Promise<void>;

    Install

    npm i clustered-cache

    DownloadsWeekly Downloads

    1

    Version

    1.1.3

    License

    ISC

    Unpacked Size

    12.2 kB

    Total Files

    14

    Last publish

    Collaborators

    • avatar