redis脚本的原子性
Atomicity of scripts
Redis uses the same Lua interpreter to run all the commands. Also Redis guarantees that a script is executed in an atomic way: no other script or Redis command will be executed while a script is being executed. This semantic is similar to the one of MULTI / EXEC. From the point of view of all the other clients the effects of a script are either still not visible or already completed.
However this also means that executing slow scripts is not a good idea. It is not hard to create fast scripts, as the script overhead is very low, but if you are going to use slow scripts you should be aware that while the script is running no other client can execute commands.
Redis使用同一个的Lua解释器来运行所有的命令。同时,Redis保证脚本以原子方式执行:在执行脚本时,不会执行其他脚本或Redis命令。这个语义类似于“MULTI”的语义。从所有其他客户端的角度来看,脚本的效果要么还不可见,要么已经完成。
然而,这也意味着执行缓慢的脚本不是一个好主意。创建快速脚本并不难,因为脚本开销非常低,但是如果您打算使用慢速脚本,您应该注意,当脚本运行时,其他客户机不能执行命令。
以上是官网的解释,从上面的解释来看,redis脚本的原子性并不是传统意义上的原子性。我们都知道,原子性是在一个事务单元内,要么所有的指令都执行,要么所有的指令都不执行,而redis的脚本原子性指的是在一个脚本执行期间,不会有该脚本之外的任何其他指令会得到执行从而影响脚本的执行结果。而又因为在脚本执行期间不会有其他任何的命令执行,从而导致其他客户端在该脚本执行期间不会得到redis中的数据状态,这样也从某种意义上实现了隔离性。
因此可以总结出redis脚本的几个特性:
- 隔离性 在脚本执行期间,其他任何客户端不会得到数据的状态。
- 半原子性 在脚本执行期间,不会有其他命令影响脚本的执行,因此在排除外力因素情况下,如果逻辑正确,可以保证脚本内的命令都得到执行。