Predis 指南 (PHP)

将 PHP 应用程序连接到 Redis 数据库

Predis是 Redis 的推荐 PHP 客户端。 以下部分介绍了如何安装Predis并将您的应用程序连接到 Redis 数据库。

注意:
尽管我们为Predis,则它是第三方 client 库,并非由 Redis 直接开发或支持。

Predis需要正在运行的 Redis 或 Redis Stack 服务器。 请参阅 Redis 安装入门 指示。

安装

使用 Composer 安装Predis图书馆 使用以下命令行:

composer require predis/predis

Connect and test

Connect to a locally-running server on the standard port (6379) with the following code:

<?php

require 'vendor/autoload.php';

use Predis\Client as PredisClient;

$r = new PredisClient([
                'scheme'   => 'tcp',
                'host'     => '127.0.0.1',
                'port'     => 6379,
                'password' => '',
                'database' => 0,
            ]);

Store and retrieve a simple string to test the connection:

echo $r->set('foo', 'bar'), PHP_EOL;
// >>> OK

echo $r->get('foo'), PHP_EOL;
// >>> bar

Store and retrieve a hash object:

$r->hset('user-session:123', 'name', 'John');
$r->hset('user-session:123', 'surname', 'Smith');
$r->hset('user-session:123', 'company', 'Redis');
$r->hset('user-session:123', 'age', 29);

echo var_export($r->hgetall('user-session:123')), PHP_EOL;
/* >>>
array (
  'name' => 'John',
  'surname' => 'Smith',
  'company' => 'Redis',
  'age' => '29',
)
*/

More information

The Predis wiki on Github has information about the different connection options you can use.

See also the pages in this section for more information and examples: