Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you perform Redis transactions in PHP?

Tags:

php

redis

  1. Without using any libraries like predis, what is the best way to do a Redis call from PHP?

    I currently use the exec command but was wondering if there was a better way.

    exec('redis-cli SET foo bar');
    
  2. Secondly, how do you perform a transaction? I can do it like so from the command line...

    $ redis-cli
    redis 127.0.0.1:6379> MULTI
    OK
    redis 127.0.0.1:6379> INCR FOO
    QUEUED
    redis 127.0.0.1:6379> INCR BAR
    QUEUED
    redis 127.0.0.1:6379> EXEC
    1) (integer) 1
    2) (integer) 1
    

    However if I tried to do it like this, each individual command gets executed separately, not within the same transaction and I end up getting the error (error) ERR EXEC without MULTI

    exec('redis-cli MULTI');
    exec('redis-cli INCR FOO');
    exec('redis-cli INCR BAR');
    exec('redis-cli EXEC');
    
like image 707
user784637 Avatar asked Mar 24 '13 04:03

user784637


2 Answers

With Predis, you'd have something like ...

$redis = new \Predis\Client('tcp://ip.address:port');
$redis->multi();
$redis->incr('foo');
$redis->incr('bar');
$redis->lrange('mylist', 0, -1);
$data = $redis->exec();

And $data might look like the following, depending what those counters were to start with ... :

[
  1, // foo 
  2, // bar   
  ['fish', 'beans', 'bar', 'baz'], // whatever was in 'mylist'    
]
like image 162
David Goodwin Avatar answered Nov 15 '22 00:11

David Goodwin


There are two ways to connect with Redis and use this library in PHP.

1) Use client-side Redis Libraries from http://redis.io/clients :- There are 5 available for PHP and you can use any one of them at your discretion and will (weighing the pros and cons of each). Once you have a client-side library in-place, its plane-jane simple. For example, with the Predis Library

require "predis/autoload.php";
Predis\Autoloader::register();
try {
    $redis = new Predis\Client(array(
    "scheme" => "tcp",
    "host" => "127.0.0.1",
        "port" => 6379));

    echo "Successfully connected to Redis";
}
catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}

Check the linked github page for more details on getting, setting and increment functions.

2) If you choose to continue using Predis from the shell, then create a shell (.sh) script on your server, place the above 4 commands (and whatever commands you'd like to execute in a transaction) in this script as below.

#!/bin/bash
#<Your transaction commands go below here>

Rename this file as <filename>.sh and execute this as a shell command using the exec function in your PHP code.

exec('sh <filename>.sh');
like image 38
verisimilitude Avatar answered Nov 15 '22 02:11

verisimilitude