Redis Lua Scripting

Redis Lua Scripting for Transactions in PHP

Welcome! In this lesson, we're exploring a powerful feature: **Lua scripting **. Using Lua scripts in Redis provides a robust method for ensuring the atomic execution of non trivial operations. This means you can bundle multiple Redis commands into a single script, ensuring they execute together without interruption.

Here's a code example demonstrating how you might use a Lua script:

<?php

require 'vendor/autoload.php';

use Predis\Client;

// Connect to the Redis server
$client = new Client();

// Define the Lua script
$luaScript = '
    local current = redis.call("get", KEYS[1])
    if current then
        current = tonumber(current)
        redis.call("set", KEYS[1], current + ARGV[1])
        return current + ARGV[1]
    else
        redis.call("set", KEYS[1], ARGV[1])
        return ARGV[1]
    end
';

try {
    // Eval the script
    $newCount = $client->eval($luaScript, 1, 'counter', 5);
    echo "New counter value: $newCount\n";
} catch (Exception $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

In the code above, we execute a Lua script atomically, ensuring all operations are performed together. We also handle potential errors during script execution with the try/catch block.

In the code row $newCount = $client->eval($luaScript, 1, 'counter', 5);, the eval method is called to execute a Lua script on the Redis server. Here's a breakdown of the parameters provided in the eval call:

  1. $luaScript: This parameter passes the Lua script code to the eval method. It contains the operations to be executed.

  2. 1: This parameter indicates the number of keys the Lua script will work with. In this context, it informs Redis that there is only one key being manipulated in the script.

  3. 'counter': This parameter is the actual key that the Lua script will operate on. It corresponds to KEYS[1] in the Lua script since Lua uses 1-based indexing.

  4. 5: This is the first argument to the Lua script (accessible within the Lua script as ARGV[1]). In the script, this value is used to increment the current value of the key counter.

Now, let's break down the Lua code used:

  • The KEYS variable holds the keys the script will work with — here, KEYS[1] is counter. Note that Lua uses 1-based indexing.
  • The ARGV variable holds the script's arguments — here, ARGV[1] is 5.

The Lua script performs these operations:

  1. Retrieve the current value of the key counter.
  2. Increment the key's value by the script argument (5) if it exists.
  3. If the key doesn't exist, set its value to 5.
  4. Utilize redis.call to perform the set operation on Redis.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal