Lock key redis and nodejs

Asked

Viewed 23 times

1

I’m having a headache with multiple processes writing in the same key. Is there any way to lock a key, both for writing and reading?

cluster.js

const cluster = require('cluster');
const cpus = require('os').cpus().length;
const client = require('redis').createClient();

client.set('num', '0');

if (cluster.isMaster) {
    console.log('Master process is running');

    for (let i = 0; i < cpus; i++) {
        cluster.fork();
    }
} else {
    require('./main.js');
}

main.ts

import * as redis from 'redis';
import * as Lock from 'redis-lock';
import { promisify } from 'util';

const config: redis.ClientOpts = {
    host: '127.0.0.1',
    port: 6379
};

const client: redis.RedisClient = new redis.RedisClient(config);
const lock = promisify(Lock(client));

(async () => {
    for (let i = 0; i < 5; i++) {
        await add();
    }
})();

async function add() {
    await new Promise<string>((resovle, reject) => {
        lock('num').then((done) => {
            client.watch('num', (err: Error) => {
                if (err) {
                    console.error(err);
                    done();
                    reject(err);
                }

                client.get('num', (err: Error, reply: string) => {
                    if (err) {
                        console.error(err);
                        done();
                        reject(err);
                    }

                    let numStr: string = reply;
                    let num: number = Number(numStr);
                    num++;

                    client.multi().set('num', num).exec((err: Error, reply: string) => {
                        if (err) {
                            console.error(err);
                            done();
                            reject(err);
                        }

                        console.log(num);
                        done();
                        resovle(reply);
                    });
                });
            });
        });
    });
};

Numbers of cpus: 4 Upshot:

1
1
1
2
3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  • Well, I was able to solve the problem https://github.com/Placidina/redis-concurrency

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.