Skip to content

Instantly share code, notes, and snippets.

@dollarkillerx
Last active April 15, 2021 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dollarkillerx/399dc15049e3165322609fa4dc749bd7 to your computer and use it in GitHub Desktop.
Save dollarkillerx/399dc15049e3165322609fa4dc749bd7 to your computer and use it in GitHub Desktop.
基于Redis实现的分布式锁

基于Redis实现的分布式锁

前言

redis真不是太适合做分布式锁

实现原理

  • 加锁 SETNX Key Value 当key不存在时赋值,反之失败
  • 锁超时 EXPIRE Key Timeout 设置key超时时间
  • 解锁DEL key

隐患

1.SETNX, EXPIRE 非原子性

通讯通过TCP与redis服务进行链接 两个的两次操作不能保证同时完成 可能造成死锁

2. EXPIRE设置固定超时时间是不可靠的

如果设置固定超时时间,可能当前A进程的操作还未完成,锁发生超时释放 B进程获得锁 导致数据冲突

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment