कुछ शोध के बाद मैं "Distributed locks using Redis" समाधान के साथ समाप्त हुआ। उस के लिए नोड मॉड्यूल है: node-redis-warlock।
आशा है कि यह उत्तर किसी और के लिए उपयोगी होगा।
अद्यतन। मिनिमल नमूना कोड:
var Warlock = require('node-redis-warlock'),
redis = require('redis');
// Establish a redis client
redis = redis.createClient();
// and pass it to warlock
var warlock = new Warlock(redis);
function executeOnce (key, callback) {
warlock.lock(key, 20000, function(err, unlock){
if (err) {
// Something went wrong and we weren't able to set a lock
return;
}
if (typeof unlock === 'function') {
setTimeout(function() {
callback(unlock);
}, 1000);
}
});
}
// Executes call back only once
executeOnce('every-three-hours-lock', function(unlock) {
// Do here any stuff that should be done only once...
unlock();
});
अद्यतन 2। अधिक विस्तृत उदाहरण:
const CronJob = require('cron').CronJob;
const Warlock = require('node-redis-warlock');
const redis = require('redis').createClient();
const warlock = new Warlock(redis);
const async = require('async');
function executeOnce (key, callback) {
warlock.lock(key, 20000, function(err, unlock) {
if (err) {
// Something went wrong and we weren't able to set a lock
return;
}
if (typeof unlock === 'function') {
setTimeout(function() {
callback(unlock);
}, 1000);
}
});
}
function everyMinuteJobTasks (unlock) {
async.parallel([
sendEmailNotifications,
updateSomething,
// etc...
],
(err) => {
if (err) {
logger.error(err);
}
unlock();
});
}
let everyMinuteJob = new CronJob({
cronTime: '*/1 * * * *',
onTick: function() {
executeOnce('every-minute-lock', everyMinuteJobTasks);
},
start: true,
runOnInit: true
});
/* Actual tasks */
let sendEmailNotifications = function(done) {
// Do stuff here
// Call done() when finished or call done(err) if error occurred
}
let updateSomething = function(done) {
// Do stuff here
// Call done() when finished or call done(err) if error occurred
}
// etc...
आप डेटाबेस पर कुछ ध्वज सत्यापित करने के लिए एक विशेष प्रक्रिया का उपयोग करने का प्रयास कर सकते हैं ताकि आप जांच सकें कि कोई व्यक्ति पहले से ही वह नौकरी लेता है और इसे फिर से नहीं लेता है। इसे डेटाबेस पर केवल कुछ पंक्तियां और एक बहुत छोटी तालिका लेनी चाहिए (या एक पंक्ति यदि आपके पास पहले से कॉन्फ़िगरेशन तालिका है)। – Gepser
हां, यह एक समाधान हो सकता है। शायद उस विषय पर कुछ उदाहरण लेख हैं? असल में मैं अलग प्रक्रिया बनाना चाहता हूं जो केवल क्रॉन जॉब निष्पादन को संभालेगी। क्या यह संभव है? – epidemiya30