是否可以检查Redis设置键是否存在,如果不存在则设置它,如果存在则退出,全部作为事务 [英] Is it possible to check if a Redis set key exists and if it doesn't exist set it, if it does exist then exit, all as a transaction

查看:82
本文介绍了是否可以检查Redis设置键是否存在,如果不存在则设置它,如果存在则退出,全部作为事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把它作为一个事务来做,因为这个密钥将作为以后操作的锁".如果发生这种情况怎么办:

I want to do this as a transaction because this key will serve as a "lock" for later actions. What if this happens:

  1. 检查它是否存在
  2. 确定它不存在
  3. 其他人检查它存在而我确定它不存在
  4. 设置它,因为它不存在,然后执行我的操作
  5. 第二人称同时进行设置,并在不应允许的情况下执行操作.

推荐答案

好吧,如果你想了解 redis 事务的本质:http://redis.io/topics/transactions

Well, if you wanted to know about the nature of redis transactions: http://redis.io/topics/transactions

特别是这部分:

"一个事务中的所有命令都被序列化并执行依次.永远不会发生另一个人发出的请求客户端在 Redis 执行过程中提供服务交易.这保证了命令作为单个隔离操作."

"All the commands in a transaction are serialized and executed sequentially. It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a single isolated operation."

如果你想要一个只在不存在时添加的命令,http://redis.io/commands/setnx 是 SETNX 文档的链接,它正是这样做的.

If you want a single command that only adds if not exists, http://redis.io/commands/setnx is the link to docs for SETNX which does exactly that.

对于事务,您首先调用 MULTI,然后发送您想要的任何命令,然后调用 EXEC 以开始执行一系列命令.这保证是原子的,在序列完成之前不能执行其他命令.

With transactions, you start by calling MULTI, then send in whatever commands you wish, then call EXEC to commence with the series of commands. This is guaranteed to be atomic, no other command can be executed until the sequence is done.

HTH

这篇关于是否可以检查Redis设置键是否存在,如果不存在则设置它,如果存在则退出,全部作为事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆