|
| 1 | +Redis supports server-side scripting using Lua (a lightweight, high-level, multi-paradigm programming language primarily designed |
| 2 | +for embedded use within applications. It's known for its simplicity, efficiency, and ease of integration with other languages, |
| 3 | +particularly C and C++), whcih allows for extending Redis' functionality and performing complex operations atomically. |
| 4 | + |
| 5 | +- Lua scripts execute as a single, atomic unit. This means that either the entire script completes successfully, or none of its |
| 6 | +operations are applied, ensuring data consistency even with multiple commands. This eliminates the need for explicit transactions |
| 7 | +or pipelines for atomicity within the script's execution. |
| 8 | + |
| 9 | +- Lua scripts can implement complex business logic, conditional execution, and custom data manipulations that aren't possible |
| 10 | +w/ individual Redis commands. They can access and modify Redis data structures and utilize most of the standard Redis commands |
| 11 | +through the redis.call() and redis.pcall() functions within the script. |
| 12 | + |
| 13 | +- Lua scripts are executed using the EVAL command, which takes the script itself, the number of keys the script will access, |
| 14 | +and then the keys and arguments as separate parameters. For subsequent executions of the same script, EVALSHA can be used with the |
| 15 | +script's SHA1 digest for efficiency, avoiding repeated transmission of the full script. |
| 16 | + |
| 17 | +- Arguments passed to a Lua script are divided into KEYS and ARGV: |
| 18 | +- KEYS are used to specify the keys the script will interact with, allowing Redis to properly route commands in a clustered environment. |
| 19 | +- ARGV contains additional arguments or data needed by the script. Within the Lua script, these are accessible as tables KEYS[1], KEYS[2], etc.., and ARGV[1], ARGV[2], etc. |
| 20 | +- Important **NOTE**: Lua tables are 1-indexed (they start at index 1 instead of 0). |
| 21 | + |
| 22 | +- Error Handling: Lua scripts can manage errors within the script itself, allowing for more robust and self-contained logic. |
| 23 | +- Use Cases: Lua scripting is particularly useful for implementing atomic operations like distributed locks, counters with conditional increments, complex data migrations, or custom commands that combine multiple Redis operations. |
| 24 | + (**Obviously in my case, I'm going to be using it for Distributed Locks**). |
0 commit comments