如何在PHP中执行Redis事务?

5
  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');
    
2个回答

9
使用Predis,您可以拥有类似于以下的东西...
$redis = new \Predis\Client('tcp://ip.address:port');
$redis->multi();
$redis->incr('foo');
$redis->incr('bar');
$redis->lrange('mylist', 0, -1);
$data = $redis->exec();

根据计数器的起始值,$data 的形式可能如下:

[
  1, // foo 
  2, // bar   
  ['fish', 'beans', 'bar', 'baz'], // whatever was in 'mylist'    
]

2

有两种方式可以连接 Redis 并在 PHP 中使用此库。

1) 使用来自http://redis.io/clients的客户端 Redis 库:- PHP 有5个可用的库,您可以根据自己的喜好和需要选择其中的任何一个(权衡每个库的优缺点)。一旦您安装了客户端库,它就非常简单。例如,使用 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();
}

请查看链接的Github页面,了解有关“获取”,“设置”和“增量”功能的更多详细信息。
2)如果您选择继续在shell中使用Predis,则在服务器上创建一个shell(.sh)脚本,将上述4个命令(以及您想要在事务中执行的任何命令)放在以下位置。
#!/bin/bash
#<Your transaction commands go below here>

将此文件重命名为<filename>.sh,并在您的PHP代码中使用exec函数将其作为shell命令执行。请保留HTML标记。
exec('sh <filename>.sh');

Predis听起来很不错,但您知道是否有任何在PHP中进行事务而不使用客户端库的方法吗? - user784637

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接