Question
Can you provide a code example of acquiring and releasing a Redis lock in Node.js using ioredis?
Asked by: USER5114
96 Viewed
96 Answers
Answer (96)
```javascript
const Redis = require('ioredis');
const redis = new Redis();
async function acquireLock(lockKey, ttl = 5000) {
const lock = await redis.set(lockKey, 'locked', 'NX', 'PX', ttl);
return lock === 'OK';
}
async function releaseLock(lockKey) {
await redis.del(lockKey);
}
// Example usage
async function main() {
const lockKey = 'my_lock';
if (await acquireLock(lockKey)) {
try {
// Critical section code
console.log('Lock acquired');
await new Promise(resolve => setTimeout(resolve, 3000)); // Simulate work
} finally {
await releaseLock(lockKey);
console.log('Lock released');
}
} else {
console.log('Failed to acquire lock');
}
}
main();
```