doushi1929 2019-06-13 22:40
浏览 158
已采纳

SETNX单实例Redis锁

I need to connect to a single Redis instance from an application client.

Since the client will be replicated in Kubernetes, I'm studying Redis documentation about locks to prevent races between the client replicas.

After some googling and reading around, I zeroed in on these two resources:

Interestingly the SETNX docs explicitly advise against using SETNX to implement locks, stating that it has basically become obsolete:

The following pattern is discouraged in favor of the Redlock algorithm [...]

We document the old pattern anyway because certain existing implementations link to this page as a reference.

However the Redlock algorithm is specifically tailored for distributed locks, thus when one seeks to lock on multiple Redis instances - they actually refer to multiple masters.

To go a bit further, the library redsync (golang) declares the New function as follows:

func New(pools []Pool) *Redsync {
    return &Redsync{
        pools: pools,
    }
}

It looks unmistakably designed to support locking on a Redis cluster.

In my use case, I'm going to connect to only one Redis instance.

Probably I can just use the redsync package and pass an array of length one, yet to me it looks like the SETNX pattern could work equally fine on a single Redis instance.

Am I seeing this correctly? Thank you

  • 写回答

1条回答 默认 最新

  • douzhui8531 2019-06-13 23:59
    关注

    Yes, it's true that the Redlock algorithm is designed for a distributed Redis system, and that if you're using a single instance it should be fine to use the simpler locking methods described in the SET and SETNX documentation.

    However, a more important point is this: you probably don't need to use locks to avoid conflicts between multiple Redis clients. Redis locks are usually used to secure some external distributed resource (see my answer here for a bit more on this). Within Redis itself locks are generally not necessary; thanks to Redis' single-threaded nature, many commands are already atomic, and you have the ability to use transactions or Lua scripts to compose arbitrarily complex atomic operations.

    So my advice is to deisgn your client code to use atomicity to avoid conflict rather than trying to use a lock (distributed or otherwise).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献