Skip to content

Instantly share code, notes, and snippets.

@solancer
Created July 11, 2024 07:57
Show Gist options
  • Save solancer/d6f8ec382fe65b82baf7ce24533b4505 to your computer and use it in GitHub Desktop.
Save solancer/d6f8ec382fe65b82baf7ce24533b4505 to your computer and use it in GitHub Desktop.
redlock - lock jobs
// 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;
// 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