Created
January 24, 2024 07:56
-
-
Save duyixian1234/f70b03b76861d54a48fa669acc7cdd88 to your computer and use it in GitHub Desktop.
etcd lock
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
| import { Etcd3 } from "etcd3"; | |
| const client = new Etcd3(); | |
| async function withLock( | |
| key: string, | |
| action: () => Promise<void>, | |
| client: Etcd3 | |
| ): Promise<void> { | |
| const lockKey = `locks/${key}`; | |
| const lock = client.lock(lockKey); | |
| const safeAction = async () => action().catch(console.error); | |
| while (true) { | |
| try { | |
| await lock.do(safeAction); | |
| return; | |
| } catch (e) { | |
| continue; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment