Search by

bonsaicode / redis

ahdavis

Redis mutex lock to ensure only one server carries out a process when duplicate servers exist (e.g. an auto-scaling group), plus helpers for the phpredis extension. Works with restrictive ACLs (no KEYS, no Lua).

Package info

bitbucket.org/bonsaicode/redis

pkg:composer/bonsaicode/redis

Statistics

Installs: 22

Dependents: 0

Suggesters: 0

2.0.0 2026-11-14 17:18 UTC

This package is auto-updated.

Last update: 2026-11-14 17:23:05 UTC


README

A single-instance Redis mutex lock, used to ensure only one server carries out a process in an environment where duplicate servers exist, e.g. a GCP auto-scaling managed instance group. Also provides helpers for some phpredis methods. The connection is stored in $GLOBALS['REDIS'], so every phpredis method can be used through it.

Works with restrictive Redis ACLs: it never uses KEYS or Lua scripting (EVAL), so the app user can have -keys -@scripting -flushall.

See https://github.com/phpredis/phpredis for more info

Dependencies

You must have a redis service running.

Requirements

Installation

To install the package, run the following command in the console:

$ composer require "bonsaicode/redis"

Usage

# Create connection with configuration.  On failure the error is logged and $GLOBALS['REDIS'] is null;
# every method below then returns a safe failure value.

$_config = [
    'redis' => [
        'host'    => '10.0.0.1', # redis server
        'port'    => 6379,
        'timeout' => 2,
        'auth'    => 'password', # optional; or [ 'user', 'password' ] for a Redis 6+ ACL user
        'dbindex' => 1           # optional, e.g. session handler uses database 0, so we use 1 for app data
    ]
];
BonsaiCode\Redis::connectSelect( $_config['redis'] );
unset( $_config['redis'] ); # remove config and password from memory

# Acquire a lock, e.g. so that only one server runs a cron job

$lockKey = 'cron1';
list( $lockAcquired, $lockValue ) = BonsaiCode\Redis::lockAcquire( $lockKey, 90 ); # lock expires after 90 seconds
if( $lockAcquired ) {
    try {
        # ... your processing here ...
    } finally {
        BonsaiCode\Redis::lockRelease( $lockKey, $lockValue ); # only releases the lock if we still hold it
    }
}

# Keys in a database (uses SCAN; note this selects that database)

$keys = BonsaiCode\Redis::dbKeysGet( 1, 'user:*' );
$kv   = BonsaiCode\Redis::dbKeysValuesGet( 1, 'user:*' );

# Monitoring: your app decides how to alert

$h = BonsaiCode\Redis::healthInfo();
if( ! $h['reachable'] ) { /* $h['error'] */ }
if( $h['memory_ratio'] >= 0.70 ) { /* $h['used_memory_human'] of $h['maxmemory_human'], $h['evicted_keys'] */ }

See examples/ for more.

Tests

composer install
composer test    # Redis tests are skipped unless ext-redis and a server (REDIS_HOST, REDIS_PORT, REDIS_AUTH, REDIS_DB=15) are available

Upgrading from 1.x

See CHANGELOG.md. flush() was removed (it ran FLUSHALL on every database).