Three, Redis Lua script execution

Preface:

  We have already analyzed how distributed lock, as well as various problems of distributed lock in the process of implementation, and proposed solutions, although we seem to achieve the above distributed lock, but there is a fatal problem, atomicity problem, either obtain the lock or release the lock, all with multi-line Redis command to achieve, if not guarantee the atomicity of this command is executed, the entire process on security issues, where we want to introduce another language Lua, Lua scripting language can be used to solve multi-line command Redis atomic problem, look at the following Lua scripting language;

First, how to perform Redis Lua script:

  1.EVAL command:

    

     Execute a script includes parameters:

      script: script content script or address;

      numkeys: the number of key used in a script, the next number will numkeys as a key parameter, as the rest of arg;

      arg: Other parameters are stored in an array ARGV scripting environment, the angle marked from the beginning;

    Example: the EVAL "return 'Hello World'" 0 , wherein

      "return 'the Hello world'" : is the content of the script, where these returns a string;

      0 : that is the key parameter is not used directly back

    effect:

      

   2, SCRIPT LOAD command:

    

    Will compile a script and cached, generates and returns a SHA1 value, for ease of use, content parameter script is the script goods address;

    The above scenario illustrates a script:

      

   3, EVALSHA command:

    

    EVAL and performed similarly to a script, the difference is sha1 value through execution of the script, the script to query the cache, then execution parameters:

      sha1 : sha1 is the script corresponding value;

    Example:

    

Second, the basic syntax of Lua script:

  Detailed syntax of Lua can refer to a number of sites online learning, columns, such as: Lua rookie tutorial to learn any language is a basic, such as: variables, data types, loops, logic, arithmetic and other aspects of grammar and Lua java there are many similarities, specifically not elaborate, and here only the most basic example of usage:

  1, declare variables:  

- test.lua script file 
A = . 5                - global variables 
local B = . 5          - local variables

   2, the print result; 

> print("Hello World!")
Hello World!
>

  3, the control condition:

IF (Boolean expressions)
 the then 
   - [boolean expression is true of the execution block of statements -] 
the else 
   - [boolean expression of the block of statements is executed to false -] 
End

  4, loop:

the while ( to true )
 do 
   Print ( " loop will always execute down " )
 End

 

    

 

Guess you like

Origin www.cnblogs.com/zouxiangzhongyan/p/11536066.html