Created
July 11, 2024 07:57
-
-
Save solancer/d6f8ec382fe65b82baf7ce24533b4505 to your computer and use it in GitHub Desktop.
redlock - lock jobs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In server/boot/redis-setup.js or any relevant file | |
const Redis = require('ioredis'); | |
const Redlock = require('redlock'); | |
// Initialize Redis | |
const redis = new Redis(); // Assumes Redis is running on default host and port | |
// Setup Redlock for distributed locks | |
const redlock = new Redlock( | |
[redis], { | |
driftFactor: 0.01, | |
retryCount: 10, | |
retryDelay: 200, | |
retryJitter: 200 | |
} | |
); | |
// Make redlock available through app object or export it | |
module.exports = redlock; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In your controller or where the function is called | |
const redlock = require('../boot/redis-setup'); // Adjust path as necessary | |
const uniqueLockKey = 'my-function-lock'; | |
const lockTtl = 1000; // Time in milliseconds | |
async function myFunction() { | |
console.log("Function is running"); | |
// Add your function's logic here | |
} | |
async function executeWithLock() { | |
try { | |
const lock = await redlock.lock(uniqueLockKey, lockTtl); | |
try { | |
await myFunction(); // Execute the function | |
} finally { | |
await lock.unlock(); // Ensure the lock is released | |
} | |
} catch (err) { | |
console.error("Failed to acquire lock or execute function:", err); | |
} | |
} | |
// If this needs to be triggered via API | |
module.exports = function(Server) { | |
Server.executeWithLock = executeWithLock; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment