Redis
There is basic Redis support in Nauthilus. Most of the time it should be enough to use simple Redis keys and string values as arguments. Type conversion can be done within Lua itself.
local nauthilus_redis = require("nauthilus_redis")
Redis custom pools
In the init script of the Nauthilus server, you can define custom pools. For each Redis command, the first parameter is either a string called "default" or a connection handle. The "default" will use Redis servers from the Nauthilus server itself.
How to register a new pool?
Register a custom pool
Syntax
local result, error = nauthilus_redis.register_redis_pool(name, mode, config)
Parameters
name(string) - Name of the new redis poolmode(string) - Defines the type of redis configuration, Possible values are:-
- standalone - Configure a simple standalone Redis instance
- cluster - Configure a Redis cluster
- sentinel - Configure a Redis sentinel
- sentinel_replica - Configure a failover client primaryly for read requests
config(table) - The configuration parameters for the new pool- address (string) - Address for the standalone system (master or replica)
- addresses (table) - List of addresses for clusters and sentinels
- master_name (string) - Master name is for sentinels
- sentinel_username (string) - Optional username for sentinels
- sentinel_password (string) - Optional password for sentinels
- username (string) - Optional username (used for standalone or sentinel setups)
- password (string) - Optional password (used for standalone or sentinel setups)
- db (number) - The database number in Redis
- pool_size (number) - Maximum number of connections in the pool
- min_idle_conns (number) - Minimum number of idle connections in the pool
- tls_enabled (boolean) - Activates TLS support
- tls_cert_file (string) - Optional path to a certificate file in PEM format
- tls_key_file (string) - Optional path to a key file in PEM format
Returns
result(string) - "OK" is returned, if the pool was configured successfully.error(string) - An error message, if an error occurs.
Example
local _, err_redis_reg = nauthilus_redis.register_redis_pool("my_custom_name", "sentinel", {
addresses = { "redis-sentinel-sentinel.ot-operators:26379" },
master_name = "myMaster",
password = "",
db = 3,
pool_size = 10,
min_idle_conns = 1,
tls_enabled = false
})
To get the handle of this pool, do the following in you Lua scripts:
local custom_pool, err_redis_client = nauthilus_redis.get_redis_connection("my_custom_name")
Now you can use custom_pool as the first argument to each Redis function.
You can define as many pools as you like. Currently supported is "standalone", "sentinel" and "cluster".
Documentation for the parameters is TODO.
In the following, I will use the name "handle" for a pool handler.
Functions
nauthilus_redis.redis_set
Stores a value in Redis with an optional expiration time.
Syntax
local result, error = nauthilus_redis.redis_set(handle, key, value, expiration)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key to store the value undervalue(string): The value to storeexpiration(number, optional): Time in seconds after which the key will expire
Returns
result(string): "OK" if the operation was successfulerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result, error = nauthilus_redis.redis_set(handle, "key", "value", 3600)
nauthilus_redis.redis_incr
Increments a numeric value stored in Redis by one.
Syntax
local number, error = nauthilus_redis.redis_incr(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key whose value should be incremented
Returns
number(number): The new value after incrementingerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local number, error = nauthilus_redis.redis_incr(handle, "key")
nauthilus_redis.redis_get
Retrieves a value from Redis by key.
Syntax
local result, error = nauthilus_redis.redis_get(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key to retrieve the value for
Returns
result(string): The value stored at the specified keyerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result, error = nauthilus_redis.redis_get(handle, "key")
nauthilus_redis.redis_expire
Sets an expiration time (in seconds) for a Redis key.
Syntax
local result, error = nauthilus_redis.redis_expire(handle, key, seconds)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key to set expiration forseconds(number): The expiration time in seconds
Returns
result(string): "OK" if the operation was successfulerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result, error = nauthilus_redis.redis_expire(handle, "key", 3600)
nauthilus_redis.redis_del
Deletes a key from Redis.
Syntax
local result, error = nauthilus_redis.redis_del(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key to delete
Returns
result(string): "OK" if the operation was successfulerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result, error = nauthilus_redis.redis_del(handle, "key")
nauthilus_redis.redis_rename
Renames a Redis key to a new name.
Syntax
local result, err = nauthilus_redis.redis_rename(handle, oldkey, newkey)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionoldkey(string): The current name of the Redis keynewkey(string): The new name for the Redis key
Returns
result(string): "OK" if the operation was successfulerr(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local oldkey = "abc"
local newkey = "def"
local result, err = nauthilus_redis.redis_rename(handle, oldkey, newkey)
nauthilus_redis.redis_hget
Retrieves a value for a specific field from a Redis hash map.
Syntax
local value, error = nauthilus_redis.redis_hget(handle, key, field)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name within the hash map
Returns
value(string): The value of the specified fielderror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local redis_key = "some_key"
local already_sent_mail, err_redis_hget = nauthilus_redis.redis_hget(handle, redis_key, "send_mail")
nauthilus_redis.redis_hset
Sets a field value in a Redis hash map.
Syntax
local result, error = nauthilus_redis.redis_hset(handle, key, field, value)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name within the hash mapvalue(string/number): The value to set for the field
Returns
result(number): 1 if field is a new field in the hash and value was set, 0 if field already exists and the value was updatederror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local redis_key = "some_key"
local result, err_redis_hset = nauthilus_redis.redis_hset(handle, redis_key, "send_mail", 1)
nauthilus_redis.redis_hdel
Deletes a field from a Redis hash map.
Syntax
local deleted, error = nauthilus_redis.redis_hdel(handle, key, field)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name to delete from the hash map
Returns
deleted(number): The number of fields that were removed (1 if successful, 0 if field did not exist)error(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result = {}
result.dovecot_session = "123"
local redis_key = "some_key"
local deleted, err_redis_hdel = nauthilus_redis.redis_hdel(handle, redis_key, result.dovecot_session)
nauthilus_redis.redis_hlen
Gets the number of fields in a Redis hash map.
Syntax
local length, error = nauthilus_redis.redis_hlen(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash map
Returns
length(number): The number of fields in the hash maperror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local redis_key = "some_key"
local length, err_redis_hlen = nauthilus_redis.redis_hlen(handle, redis_key)
nauthilus_redis.redis_hgetall
Retrieves all fields and values from a Redis hash map.
Syntax
local hash_table, error = nauthilus_redis.redis_hgetall(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash map
Returns
hash_table(table): A Lua table containing all field-value pairs from the hash maperror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local redis_key = "some_key"
local all_sessions, err_redis_hgetall = nauthilus_redis.redis_hgetall(handle, redis_key)
nauthilus_redis.redis_hincrby
Increments the integer value of a field in a Redis hash map by a specified amount.
Syntax
local new_value, error = nauthilus_redis.redis_hincrby(handle, key, field, increment)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name within the hash mapincrement(number): The integer value to increment by
Returns
new_value(number): The new value of the field after the increment operationerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local field = "some_field"
local increment = 1
local new_value, err = nauthilus_redis.redis_hincrby(handle, key, field, increment)
nauthilus_redis.redis_hincrbyfloat
Increments the floating-point value of a field in a Redis hash map by a specified amount.
Syntax
local new_value, error = nauthilus_redis.redis_hincrbyfloat(handle, key, field, increment)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name within the hash mapincrement(number): The floating-point value to increment by
Returns
new_value(string): The new value of the field after the increment operation (as a string representation of the float)error(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local field = "some_field"
local increment = 1.3
local new_value, err = nauthilus_redis.redis_hincrbyfloat(handle, key, field, increment)
nauthilus_redis.redis_hexists
Checks if a field exists in a Redis hash map.
Syntax
local exists, error = nauthilus_redis.redis_hexists(handle, key, field)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the hash mapfield(string): The field name to check for existence
Returns
exists(number): 1 if the field exists in the hash, 0 if it does not existerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local field = "some_field"
local exists, err = nauthilus_redis.redis_hexists(handle, key, field)
nauthilus_redis.redis_sadd
Adds a member to a Redis set.
Syntax
local added, error = nauthilus_redis.redis_sadd(handle, key, value)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the setvalue(string): The value to add to the set
Returns
added(number): 1 if the member was added to the set, 0 if it was already a membererror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local value = "some_value"
local added, err = nauthilus_redis.redis_sadd(handle, key, value)
nauthilus_redis.redis_sismember
Checks if a value is a member of a Redis set.
Syntax
local is_member, error = nauthilus_redis.redis_sismember(handle, key, value)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the setvalue(string): The value to check for membership
Returns
is_member(number): 1 if the value is a member of the set, 0 if it is noterror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local value = "some_value"
local is_member, err = nauthilus_redis.redis_sismember(handle, key, value)
nauthilus_redis.redis_smembers
Retrieves all members from a Redis set.
Syntax
local members, error = nauthilus_redis.redis_smembers(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the set
Returns
members(table): A Lua table containing all members of the seterror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local members, err = nauthilus_redis.redis_smembers(handle, key)
nauthilus_redis.redis_srem
Removes a member from a Redis set.
Syntax
local removed, error = nauthilus_redis.redis_srem(handle, key, value)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the setvalue(string): The value to remove from the set
Returns
removed(number): 1 if the member was removed from the set, 0 if it was not a membererror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local value = "some_value"
local removed, err = nauthilus_redis.redis_srem(handle, key, value)
nauthilus_redis.redis_scard
Returns the number of members in a Redis set.
Syntax
local count, error = nauthilus_redis.redis_scard(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the set
Returns
count(number): The number of members in the seterror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local key = "some_key"
local count, err = nauthilus_redis.redis_scard(handle, key)
nauthilus_redis.redis_upload_script
Uploads a Lua script to a Redis server for later execution.
Syntax
local sha1, error = nauthilus_redis.redis_upload_script(handle, script, script_name)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionscript(string): The Lua script to upload to the Redis serverscript_name(string): A name to identify the script for later execution
Returns
sha1(string): The SHA1 hash of the script, used to identify it when executingerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local script = [[
local redis_key = KEYS[1]
local send_mail = redis.call('HGET', redis_key, 'send_mail')
if send_mail == false then
redis.call('HSET', redis_key, 'send_mail', '1')
return {'send_email', redis_key}
else
return {'email_already_sent'}
end
]]
local upload_script_name = "nauthilus_send_mail_hash"
local sha1, err_upload = nauthilus_redis.redis_upload_script(handle, script, upload_script_name)
Use an init script to upload scripts at startup
nauthilus_redis.redis_run_script
Executes a Lua script on a Redis server, either by providing the script directly or by referencing a previously uploaded script.
Syntax
local result, error = nauthilus_redis.redis_run_script(handle, script, script_name, keys, args)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionscript(string): The Lua script to execute (leave empty if using script_name)script_name(string): The name of a previously uploaded script (leave empty if providing script directly)keys(table): A Lua table containing the Redis keys that will be accessed by the scriptargs(table): A Lua table containing additional arguments for the script
Returns
result(any): The result returned by the executed scripterror(string): An error message if the operation fails
Example
local redis_key = "some_redis_key"
local script = ""
local upload_script_name = "nauthilus_send_mail_hash"
-- Set either script or upload_script_name!
local script_result, err_run_script = nauthilus_redis.redis_run_script(handle, script, upload_script_name, { redis_key }, {})
If running a script, you must set the upload-script-name to ""
nauthilus_redis.redis_zadd
New in version 1.4.10
Adds members with their associated scores to a Redis Sorted Set.
Syntax
local result, err = nauthilus_redis.redis_zadd(key, members)
Parameters
key(string): The name of the Redis Sorted Set.members(table): A Lua table where:- Keys are the members (strings).
- Values are the scores (numbers).
Returns
result(number): The total number of members successfully added.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local added, err = nauthilus_redis.redis_zadd("my_sorted_set", { member1 = 10, member2 = 20 })
if err then
print("Error:", err)
else
print("Added elements:", added)
end
nauthilus_redis.redis_zrange
New in version 1.4.10
Retrieves a subset of elements from a Redis Sorted Set based on an index range (in ascending order).
Syntax
local elements, err = nauthilus_redis.redis_zrange(key, start, stop)
Parameters
key(string): The name of the Redis Sorted Set.start(number): The starting index of the range.stop(number): The stopping index of the range.
Returns
elements(table): A Lua table containing the retrieved elements.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local elements, err = nauthilus_redis.redis_zrange("my_sorted_set", 0, -1)
if err then
print("Error:", err)
else
for _, val in ipairs(elements) do
print(val)
end
end
nauthilus_redis.redis_zrevrange
New in version 1.4.10
Retrieves a subset of elements from a Redis Sorted Set in descending order based on an index range.
Syntax
local elements, err = nauthilus_redis.redis_zrevrange(key, start, stop)
Parameters
key(string): The name of the Redis Sorted Set.start(number): The starting index of the range.stop(number): The stopping index of the range.
Returns
elements(table): A Lua table containing the retrieved elements.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local elements, err = nauthilus_redis.redis_zrevrange("my_sorted_set", 0, -1)
if err then
print("Error:", err)
else
for _, val in ipairs(elements) do
print(val)
end
end
nauthilus_redis.redis_zrangebyscore
New in version 1.4.10
Retrieves elements within a score range from a Redis Sorted Set. Optional pagination is supported.
Syntax
local elements, err = nauthilus_redis.redis_zrangebyscore(key, min_score, max_score, options)
Parameters
key(string): The name of the Redis Sorted Set.min_score(number): The lower bound of the score range.max_score(number): The upper bound of the score range.options(table, optional): A Lua table for optional pagination:offset(number): The starting position of the results.count(number): The maximum number of results retrieved.
Returns
elements(table): A Lua table containing the retrieved elements.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local elements, err = nauthilus_redis.redis_zrangebyscore("my_sorted_set", 10, 50, { offset = 0, count = 5 })
if err then
print("Error:", err)
else
for _, val in ipairs(elements) do
print(val)
end
end
nauthilus_redis.redis_zrem
New in version 1.4.10
Removes members from a Redis Sorted Set.
Syntax
local result, err = nauthilus_redis.redis_zrem(key, members)
Parameters
key(string): The name of the Redis Sorted Set.members(table): A Lua table containing the members (as strings) to be removed.
Returns
result(number): The number of members successfully removed.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local removed, err = nauthilus_redis.redis_zrem("my_sorted_set", { "member1", "member2" })
if err then
print("Error:", err)
else
print("Removed elements:", removed)
end
nauthilus_redis.redis_zrank
New in version 1.4.10
Gets the rank of a member in a Redis Sorted Set, with scores sorted in ascending order.
Syntax
local rank, err = nauthilus_redis.redis_zrank(key, member)
Parameters
key(string): The name of the Redis Sorted Set.member(string): The member whose rank you want to retrieve.
Returns
rank(number): The rank of the member (0-based index).err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local rank, err = nauthilus_redis.redis_zrank("my_sorted_set", "member1")
if err then
print("Error:", err)
else
print("Rank of member:", rank)
end
nauthilus_redis.redis_zrevrank
New in version 1.7.20
Gets the rank of a member in a Redis Sorted Set, with scores sorted in descending order (highest score has rank 0).
Syntax
local rank, err = nauthilus_redis.redis_zrevrank(handle, key, member)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The name of the Redis Sorted Setmember(string): The member whose rank you want to retrieve
Returns
rank(number): The rank of the member (0-based index, with 0 being the highest score)err(string): An error message if the operation fails or if the member does not exist
Example
local nauthilus_redis = require("nauthilus_redis")
local rank, err = nauthilus_redis.redis_zrevrank("default", "my_sorted_set", "member1")
if err then
print("Error:", err)
else
print("Reverse rank of member:", rank)
end
nauthilus_redis.redis_zremrangebyscore
New in version 1.4.10
Removes all members within a given score range from a Redis Sorted Set.
Syntax
local result, err = nauthilus_redis.redis_zremrangebyscore(key, min_score, max_score)
Parameters
key(string): The name of the Redis Sorted Set.min_score(number): The lower bound of the score range.max_score(number): The upper bound of the score range.
Returns
result(number): The number of members removed.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
local removed, err = nauthilus_redis.redis_zremrangebyscore("my_sorted_set", 10, 20)
if err then
print("Error:", err)
else
print("Removed elements:", removed)
end
nauthilus_redis.redis_zremrangebyrank
New in version 1.7.20
Removes all members within a given rank range from a Redis Sorted Set.
Syntax
local result, err = nauthilus_redis.redis_zremrangebyrank(handle, key, start, stop)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The name of the Redis Sorted Set.start(number): The start position (0-based, inclusive). Can be negative, where -1 is the last element.stop(number): The stop position (0-based, inclusive). Can be negative, where -1 is the last element.
Returns
result(number): The number of members removed.err(string): An error message, if an error occurs.
Example
local nauthilus_redis = require("nauthilus_redis")
-- Remove the first three elements (ranks 0, 1, 2)
local removed, err = nauthilus_redis.redis_zremrangebyrank("default", "my_sorted_set", 0, 2)
if err then
print("Error:", err)
else
print("Removed elements:", removed)
end
-- Remove the last three elements
local removed, err = nauthilus_redis.redis_zremrangebyrank("default", "my_sorted_set", -3, -1)
if err then
print("Error:", err)
else
print("Removed elements:", removed)
end
nauthilus_redis.redis_zcount
New in version 1.7.7
Counts the number of members in a Redis Sorted Set with scores between min and max.
Syntax
local count, err = nauthilus_redis.redis_zcount(handle, key, min, max)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The name of the Redis Sorted Setmin(string): The minimum score (can be a number or "-inf")max(string): The maximum score (can be a number or "+inf")
Returns
count(number): The number of members in the specified score rangeerr(string): An error message, if an error occurs
Example
local nauthilus_redis = require("nauthilus_redis")
local count, err = nauthilus_redis.redis_zcount("default", "my_sorted_set", "10", "20")
if err then
print("Error:", err)
else
print("Number of members in range:", count)
end
nauthilus_redis.redis_zscore
New in version 1.7.7
Retrieves the score of a member in a Redis Sorted Set.
Syntax
local score, err = nauthilus_redis.redis_zscore(handle, key, member)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The name of the Redis Sorted Setmember(string): The member whose score you want to retrieve
Returns
score(number): The score of the member in the sorted seterr(string): An error message if the operation fails or if the member does not exist
Example
local nauthilus_redis = require("nauthilus_redis")
local score, err = nauthilus_redis.redis_zscore("default", "my_sorted_set", "member1")
if err then
print("Error:", err)
else
print("Score of member:", score)
end
nauthilus_redis.redis_zincrby
New in version 1.7.18
Increments the score of a member in a Redis Sorted Set by the specified increment value.
Syntax
local new_score, err = nauthilus_redis.redis_zincrby(handle, key, increment, member)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The name of the Redis Sorted Setincrement(number): The value to increment the score by (can be negative to decrement)member(string): The member whose score you want to increment
Returns
new_score(number): The new score of the member after the incrementerr(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local new_score, err = nauthilus_redis.redis_zincrby("default", "top_failed_logins", 1, "username")
if err then
print("Error:", err)
else
print("New score after increment:", new_score)
end
nauthilus_redis.redis_lpush
New in version 1.7.7
Adds one or more values to the beginning of a Redis list and returns the length of the list after the push operation.
Syntax
local length, error = nauthilus_redis.redis_lpush(handle, key, value1, value2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the listvalue1(string/number): The first value to add to the beginning of the listvalue2, ...(string/number, optional): Additional values to add to the beginning of the list
Returns
length(number): The length of the list after the push operationerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local length, err = nauthilus_redis.redis_lpush("default", "my_list", "value1", "value2")
if err then
print("Error:", err)
else
print("List length after push:", length)
end
nauthilus_redis.redis_rpush
New in version 1.7.7
Adds one or more values to the end of a Redis list and returns the length of the list after the push operation.
Syntax
local length, error = nauthilus_redis.redis_rpush(handle, key, value1, value2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the listvalue1(string/number): The first value to add to the end of the listvalue2, ...(string/number, optional): Additional values to add to the end of the list
Returns
length(number): The length of the list after the push operationerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local length, err = nauthilus_redis.redis_rpush("default", "my_list", "value1", "value2")
if err then
print("Error:", err)
else
print("List length after push:", length)
end
nauthilus_redis.redis_lpop
New in version 1.7.7
Removes and returns the first element of a Redis list.
Syntax
local value, error = nauthilus_redis.redis_lpop(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the list
Returns
value(string): The value of the first element of the listerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local value, err = nauthilus_redis.redis_lpop("default", "my_list")
if err then
print("Error:", err)
else
print("Popped value:", value)
end
nauthilus_redis.redis_rpop
New in version 1.7.7
Removes and returns the last element of a Redis list.
Syntax
local value, error = nauthilus_redis.redis_rpop(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the list
Returns
value(string): The value of the last element of the listerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local value, err = nauthilus_redis.redis_rpop("default", "my_list")
if err then
print("Error:", err)
else
print("Popped value:", value)
end
nauthilus_redis.redis_lrange
New in version 1.7.7
Returns a range of elements from a Redis list.
Syntax
local elements, error = nauthilus_redis.redis_lrange(handle, key, start, stop)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the liststart(number): The starting index of the range (0-based)stop(number): The ending index of the range (inclusive, can be negative to count from the end)
Returns
elements(table): A Lua table containing the elements in the specified rangeerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local elements, err = nauthilus_redis.redis_lrange("default", "my_list", 0, -1)
if err then
print("Error:", err)
else
for i, value in ipairs(elements) do
print(i, value)
end
end
nauthilus_redis.redis_llen
New in version 1.7.7
Returns the length of a Redis list.
Syntax
local length, error = nauthilus_redis.redis_llen(handle, key)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): The Redis key of the list
Returns
length(number): The length of the listerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local length, err = nauthilus_redis.redis_llen("default", "my_list")
if err then
print("Error:", err)
else
print("List length:", length)
end
nauthilus_redis.redis_mget
New in version 1.7.7
Retrieves the values of multiple keys from Redis.
Syntax
local values, error = nauthilus_redis.redis_mget(handle, key1, key2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey1, key2, ...(string): One or more Redis keys to retrieve values for
Returns
values(table): A Lua table where keys are the Redis keys and values are the corresponding valueserror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local values, err = nauthilus_redis.redis_mget("default", "key1", "key2", "key3")
if err then
print("Error:", err)
else
for key, value in pairs(values) do
print(key, value)
end
end
nauthilus_redis.redis_mset
New in version 1.7.7
Sets multiple key-value pairs in Redis.
Syntax
local result, error = nauthilus_redis.redis_mset(handle, key1, value1, key2, value2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey1, value1, key2, value2, ...(string/number): Key-value pairs to set in Redis
Returns
result(string): "OK" if the operation was successfulerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local result, err = nauthilus_redis.redis_mset("default", "key1", "value1", "key2", "value2")
if err then
print("Error:", err)
else
print("Result:", result)
end
nauthilus_redis.redis_keys
New in version 1.7.7
Returns all keys matching a pattern.
Syntax
local keys, error = nauthilus_redis.redis_keys(handle, pattern)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionpattern(string): The pattern to match keys against (e.g., "user:*")
Returns
keys(table): A Lua table containing all keys matching the patternerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local keys, err = nauthilus_redis.redis_keys("default", "user:*")
if err then
print("Error:", err)
else
for i, key in ipairs(keys) do
print(i, key)
end
end
The KEYS command should be used with caution in production environments as it may impact performance when executed against large databases.
nauthilus_redis.redis_scan
New in version 1.7.7
Incrementally iterates over keys in Redis.
Syntax
local result, error = nauthilus_redis.redis_scan(handle, cursor, match, count)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectioncursor(number): The cursor to start the scan from (use 0 for the first call)match(string, optional): The pattern to match keys against (default: "*")count(number, optional): The number of keys to return per call (default: 10)
Returns
result(table): A Lua table with two fields:cursor(number): The cursor to use for the next scan (0 when the scan is complete)keys(table): A Lua table containing the keys found in this scan
error(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local cursor = 0
repeat
local result, err = nauthilus_redis.redis_scan("default", cursor, "user:*", 10)
if err then
print("Error:", err)
break
end
cursor = result.cursor
for i, key in ipairs(result.keys) do
print(i, key)
end
until cursor == 0
The SCAN command is the recommended way to iterate over keys in a production environment as it has minimal impact on performance.
HyperLogLog (HLL)
New in version 1.8.4
The following functions provide access to the Redis HyperLogLog data structure. Use cases include approximate distinct counts with minimal memory usage. When using Redis Cluster, note that PFMERGE requires all keys to hash to the same slot; see the note under redis_pfmerge.
nauthilus_redis.redis_pfadd
Adds the specified elements to the specified HyperLogLog (HLL) key.
Syntax
local result, error = nauthilus_redis.redis_pfadd(handle, key, element1, element2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey(string): HyperLogLog keyelement1, element2, ...(string/number): One or more elements to add
Returns
result(number): 1 if at least one internal HLL register was modified, 0 otherwiseerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local added, err = nauthilus_redis.redis_pfadd("default", "hll:unique-users", "alice", "bob", "alice")
if err then
print("Error:", err)
else
print("Registers changed:", added)
end
nauthilus_redis.redis_pfcount
Returns the approximated cardinality of the HyperLogLog(s). With multiple keys, returns the approximated cardinality of their union.
Syntax
local count, error = nauthilus_redis.redis_pfcount(handle, key1, key2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectionkey1, key2, ...(string): One or more HLL keys
Returns
count(number): The approximated cardinalityerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local count, err = nauthilus_redis.redis_pfcount("default", "hll:unique-users")
if err then
print("Error:", err)
else
print("Approx. unique users:", count)
end
nauthilus_redis.redis_pfmerge
Merges multiple HyperLogLogs into a destination key.
Syntax
local result, error = nauthilus_redis.redis_pfmerge(handle, dest_key, source_key1, source_key2, ...)
Parameters
handle(userdata/string): Redis connection handle or "default" for the default connectiondest_key(string): Destination HLL keysource_key1, source_key2, ...(string): One or more source HLL keys to merge into the destination
Returns
result(string): "OK" on successerror(string): An error message if the operation fails
Example
local nauthilus_redis = require("nauthilus_redis")
local ok, err = nauthilus_redis.redis_pfmerge("default", "hll:dst", "hll:src1", "hll:src2")
if err then
print("Error:", err)
else
print("Merge:", ok)
end
Redis Cluster users: PFMERGE requires all keys (dest and sources) to hash to the same slot. Use a common hash tag in your keys (e.g., {mytag}:hll:dst and {mytag}:hll:src1) to avoid CROSSSLOT errors.
nauthilus_redis.redis_pipeline (since 1.8.8)
Execute multiple Redis commands in a single network round-trip using pipelining. This significantly reduces latency for Lua hooks/filters that otherwise would perform many individual Redis operations.
Syntax
local results, err = nauthilus_redis.redis_pipeline(handle_or_"default", mode, commands)
Parameters
handle_or_"default"(userdata|string): A Redis connection handle returned byget_redis_connection(name), or the string"default"to use the server's default pool. The pipeline will respect the given handle (including specific pool and deployment type: standalone, sentinel, cluster).mode(string): Either"write"or"read". This affects which default client is chosen when"default"is passed and helps picking suitable connections (e.g., read replicas vs. primary) if the handle is not a concrete client.commands(array table): An array of command-tuples. Each entry is a table where the first element is the command name (lowercase string), followed by arguments. Example:{ {"set", "k", "v", 60}, {"hget", "hash", "field"} }.
Supported commands in pipelines
- Connection and strings:
ping,get,set,incr,del,expire,exists,mget,mset,keys,scan - Hashes:
hget,hset,hdel,hlen,hgetall,hincrby,hincrbyfloat,hexists - Sets:
sadd,sismember,smembers,srem,scard - Sorted sets:
zadd,zrem,zrank,zrange,zrevrange,zrangebyscore,zremrangebyscore,zremrangebyrank,zcount,zscore,zrevrank,zincrby - Lists:
lpush,rpush,lpop,rpop,lrange,llen - HyperLogLog:
pfadd,pfcount,pfmerge - Scripts:
run_script(alias:evalsha) — use an uploaded script name (seeredis_upload_script) and pass keys/args tables
Notes
- For
zrangebyscoreyou can pass an optional options table as 5th argument:{offset = N, count = M}. - For
run_script/evalshathe tuple is:{ "run_script", uploadName, {keys...}, {args...} }. TheuploadNamemust have been previously registered viaredis_upload_script(handle, scriptStr, uploadName). - For
mgetandmsetyou may pass keys/kv either as varargs or a table; both are supported. - When using Redis Cluster, the implementation transparently ensures keys for script calls use the same hash slot where needed.
Returns
results(table): Array-like table with one entry per pipelined command, in the same order. Each entry is a structured table:{ ok = boolean, value = <Lua value>|nil, err = <string>|nil }.ok = trueandvalue = nilencodes Redis NIL (e.g., GET missing key), not an error.ok = falseanderrset encodes a per-command error (e.g., WRONGTYPE). In this casevaluemay be absent or nil.- For collection-returning commands (
smembers,lrange,hgetall,zrange,mget, etc.),valueis a Lua table. - Special case
scan:valueis a table{ keys = { ... }, cursor = <number> }whenok = true.
err(string|nil):nilon success; otherwise a pipeline-wide error message. If any command is unsupported or building/ execution fails,erris returned andresultswill benil.
Examples
Minimal example with strings and hashes:
local R = require("nauthilus_redis")
local h = R.get_redis_connection("default")
local res, err = R.redis_pipeline(h, "write", {
{"set", "my:key", "value", 60}, -- EX 60
{"hset", "my:hash", "field", "v"},
{"get", "my:key"}, -- will return later in results[3]
{"hexists", "my:hash", "field"}, -- results[4] is true/false
})
assert(not err, err)
-- Structured results:
-- res[1] = { ok=true, value="OK" }
-- res[2] = { ok=true, value=1 }
-- res[3] = { ok=true, value="value" }
-- res[4] = { ok=true, value=true }
Running a batched write with a Lua script:
local R = require("nauthilus_redis")
-- Upload or ensure the script is uploaded elsewhere in initialization code:
-- R.redis_upload_script(h, [[ return redis.call('PING') ]], 'PingScript')
local t = os.time()
local res, err = R.redis_pipeline("default", "write", {
{"run_script", "ZAddRemExpire", {"app:zset"}, {t, "member", 0, t-60, 120}},
{"expire", "another:key", 3600},
})
if err then error(err) end
Behavior and performance considerations
- The pipeline executes against the specific client associated with the provided handle. If you pass the string
"default", the implementation chooses a client based onmode(readuses read handle when available;writeuses the primary/write handle). - All commands are queued and then executed with a single
EXEC-like pipeline round-trip. This reduces latency and server load. - Metrics: internal Prometheus counters for Redis reads/writes are incremented per queued command.
- Error handling: If building the batch fails (e.g., unsupported command name, missing uploaded script) an error is returned
without executing the pipeline. If execution returns an error (e.g., network issue), it is propagated as
err.