Last active
September 8, 2023 21:30
-
-
Save stoneparker/075707f48c6ef39e20f6e2921542531b to your computer and use it in GitHub Desktop.
Lock with Redis - Node.js
This file contains 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
const Redis = require('ioredis'); | |
const redis = new Redis(); | |
// Função para adquirir um lock | |
async function acquireLock(lockName, timeout) { | |
const lockKey = `lock:${lockName}`; | |
const identifier = Math.random().toString(36).slice(2); | |
const result = await redis.set(lockKey, identifier, 'PX', timeout, 'NX'); | |
if (result === 'OK') { | |
return identifier; | |
} else { | |
throw new Error('Failed to acquire lock'); | |
} | |
} | |
// Função para liberar um lock | |
async function releaseLock(lockName, identifier) { | |
const lockKey = `lock:${lockName}`; | |
const currentValue = await redis.get(lockKey); | |
if (currentValue === identifier) { | |
await redis.del(lockKey); | |
} else { | |
throw new Error('Lock is held by another process'); | |
} | |
} | |
// Exemplo de uso: | |
(async () => { | |
try { | |
const identifier = await acquireLock('meuRecurso', 5000); | |
console.log('Lock adquirido com sucesso:', identifier); | |
// Realize a operação crítica aqui | |
await releaseLock('meuRecurso', identifier); | |
console.log('Lock liberado com sucesso.'); | |
} catch (err) { | |
console.error('Erro:', err.message); | |
} finally { | |
await redis.quit(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment