问题描述
我的计划是将一些现有的Redis密钥存储在哈希中,稍后再从Redis Lua脚本中获取并采取行动.我读到,最好的做法是提供调用EVAL
时脚本中使用的所有键.
My plan is to store some existing Redis keys in a hash, that would be later fetched from within a Redis Lua script and acted upon. I read that it is best practice to provide all keys that are used in a script when invoking EVAL
.
我的问题是,运行在运行EVAL
时没有提供任何键,但是对从内脚本中获取的某些键进行操作的脚本是否安全?如果没有,后果是什么,如何避免这一缺点?
My question is, is it safe to run a script that doesn't have any keys provided when running EVAL
, but operates on some keys that are fetched from within the script? If not, what are the consequences and how can I avoid this shortcoming?
我提到在EVAL
时,无法知道特定哈希中的键是什么.我可以在EVAL
之前的一个步骤中从哈希中获取所有密钥,然后将它们提供给EVAL
,但这听起来像是过分杀了.
I mention that at the time of EVAL
, there is no way of knowing what the keys in that specific hash are. I can get all the keys from the hash in a step prior to EVAL
, then provide them to EVAL
, but that sounds like overkill.
推荐答案
由于文档中的含糊不清,这个问题经常被问到(请参阅和),但是我将在这种情况下尝试指定实际的规则控制Redis脚本中键的使用.
Because of the ambiguity in the documentation this question gets asked a lot (see this and this, for example), but I'll use this occasion to try and specify the actual rule governing the use of keys in Redis scripts.
实际规则是这样的:您的脚本只能访问驻留在单个服务器上的密钥,Redis必须知道该服务器是什么,以便可以将脚本路由到该服务器.
如果您不使用Redis Cluster,则始终会满足这些条件,因为只有一台服务器.
If you're not using Redis Cluster then these conditions will always be met, since there's only one server.
如果使用Redis Cluster,则必须指定至少一个密钥,并且脚本使用的所有密钥必须与指定的密钥位于同一服务器上.
If you are using Redis Cluster, then you must specify at least one key, and all keys that the script uses must be located on the same server as the specified keys.
因此,请回答您的问题:如果您不使用群集,您的脚本将可以正常工作.结果是,如果您以后切换到群集,它将无法正常工作,因为Redis不知道将脚本发送到哪里.
So to answer your question: your script will work fine if you're not using Cluster. The consequences are that it won't work if you later switch to Cluster, since Redis won't know where to send the script.
Redis也可能会更改为执行记录的规则,从而使所有动态生成密钥的脚本无效.我认为这将是一个严重的错误,而且我认为这不会发生.但是,如果没有其他规定,则指定密钥对于文档很有用,因此,如果我碰巧事先知道密钥,我总是这样做.
It's also possible that Redis could change to enforcing the documented rule, rendering invalid all scripts that dynamically generate keys. In my opinion that would be a bad mistake, and I don't think it will happen. But specifying the keys is useful as documentation, if nothing else, so I always do it if I happen to know the keys in advance.
这篇关于您是否需要在Redis脚本中提前声明密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!