bonsaicode/redis

Implementation of the Redis Redlock algorithm, which is used to ensure only one server carries out a process in an environment where multiple duplicate servers exist, e.g. GCP auto-scaling load balancer.

1.0.4 2020-09-20 00:10 UTC

This package is auto-updated.

Last update: 2024-06-20 08:08:12 UTC


README

Implementation of the Redis Redlock algorithm, which is used to ensure only one server carries out a process in an environment where multiple duplicate servers exist, e.g. GCP auto-scaling load balancer. Also provides a wrapper for some phpredis methods. All phpredis methods can be used through this wrapper. This wrapper creates and uses a redis object in $GLOBALS['REDIS'].

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

Dependencies:

You must have a redis service running.

Requirements

Installation

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

$ composer require "bonsaicode/redis"

Usage

# Create connection with configuration

$_config = [
    'redis' => [
        'host'    => '10.0.0.1', # redis server
        'port'    => 6379,
        'timeout' => 2,
        'auth'    => 'password', # needed if your redis requires it, also needs to be in /etc/redis.conf and /etc/php.d/50-redis.ini - session.save_path
        'dbindex' => 1 # optional, 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 lock

$lockKey = 'cron1';
list( $lockAcquired, $lockValue ) = BonsaiCode\Redis::lockAcquire( $lockKey );
if( $lockAcquired ) {

	... your processing here ...

        # release lock 
    
	BonsaiCode\Redis::lockRelease( $lockKey, $lockValue );
}

see test/Redis.php for more examples