Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

predis

> 数据库
Open source

A flexible and feature-complete Redis/Valkey client for PHP.

7.8K stars0 likes3 views
WebsiteGitHub

About

A flexible and feature-complete Redis/Valkey client for PHP.

Predis

![Software license][ico-license] [![Latest stable][ico-version-stable]][link-releases] [![Latest development][ico-version-dev]][link-releases] [![Monthly installs][ico-downloads-monthly]][link-downloads] [![Build status][ico-build]][link-actions] [![Coverage Status][ico-coverage]][link-coverage]

A flexible and feature-complete Redis / Valkey client for PHP 7.2 and newer.

More details about this project can be found on the frequently asked questions.

Main features

  • Support for Redis from 3.0 to 8.0.
  • Support for clustering using client-side sharding and pluggable keyspace distributors.
  • Support for redis-cluster (Redis >= 3.0).
  • Support for master-slave replication setups and redis-sentinel.
  • Transparent key prefixing of keys using a customizable prefix strategy.
  • Command pipelining on both single nodes and clusters (client-side sharding only).
  • Abstraction for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= 2.2).
  • Abstraction for Lua scripting (Redis >= 2.6) and automatic switching between EVALSHA or EVAL.
  • Abstraction for Hinted Hash Templates (HIMPORT, Redis >= 8.10) with automatic per-connection fieldset replay.
  • Abstraction for SCAN, SSCAN, ZSCAN and HSCAN (Redis >= 2.8) based on PHP iterators.
  • Connections are established lazily by the client upon the first command and can be persisted.
  • Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets.
  • Support for custom connection classes for providing different network or protocol backends.
  • Flexible system for defining custom commands and override the default ones.

How to install and use Predis

This library can be found on Packagist for an easier management of projects dependencies using Composer. Compressed archives of each release are available on GitHub.

bash
composer require predis/predis

Loading the library

Predis relies on the autoloading features of PHP to load its files when needed and complies with the PSR-4 standard. Autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility:

php
// Prepend a base path if Predis is not available in your "include_path".
require 'Predis/Autoloader.php';

Predis\Autoloader::register();

Connecting to Redis

When creating a client instance without passing any connection parameter, Predis assumes 127.0.0.1 and 6379 as default host and port. The default timeout for the connect() operation is 5 seconds:

php
$client = new Predis\Client();
$client->set('foo', 'bar');
$value = $client->get('foo');

Connection parameters can be supplied either in the form of URI strings or named arrays. The latter is the preferred way to supply parameters, but URI strings can be useful when parameters are read from non-structured or partially-structured sources:

php
// Parameters passed using a named array:
$client = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '10.0.0.1',
    'port'   => 6379,
]);

// Same set of parameters, passed using an URI string:
$client = new Predis\Client('tcp://10.0.0.1:6379');

Password protected servers can be accessed by adding password to the parameters set. When ACLs are enabled on Redis >= 6.0, both username and password are required for user authentication.

It is also possible to connect to local instances of Redis using UNIX domain sockets, in this case the parameters must use the unix scheme and specify a path for the socket file:

php
$client = new Predis\Client(['scheme' => 'unix', 'path' => '/path/to/redis.sock']);
$client = new Predis\Client('unix:/path/to/redis.sock');

The client can leverage TLS/SSL encryption to connect to secured remote Redis instances without the need to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on various cloud hosting providers. Encryption can be enabled with using the tls scheme and an array of suitable options passed via the ssl parameter:

php
// Named array of connection parameters:
$client = new Predis\Client([
  'scheme' => 'tls',
  'ssl'    => ['cafile' => 'private.pem', 'verify_peer' => true],
]);

// Same set of parameters, but using an URI string:
$client = new Predis\Client('tls://127.0.0.1?ssl[cafile]=private.pem&ssl[verify_peer]=1');

The connection schemes redis (alias of tcp) and rediss (alias of tls) are also supported, with the difference that URI strings containing these schemes are parsed following the rules described on their respective IANA provisional registration documents.

Since Redis 8.6, you can authenticate a client using the Subject CN from its TLS client certificate (mTLS). When this is enabled on the server, the client is authenticated during the TLS handshake, so you don’t need to send an AUTH command.

To use this, configure:

  • a CA certificate used to verify the server certificate (cafile),
  • a client certificate (local_cert) signed by a CA trusted by the Redis server for client authentication,
  • the corresponding private key (local_pk).

Make sure:

  • the Redis server certificate is signed by a CA trusted by the client, and
  • the client certificate is signed by a CA trusted by the Redis server (mTLS).
…

The actual list of supported connection parameters can vary depending on each connection backend so it is recommended to refer to their specific documentation or implementation for details.

Predis can aggregate multiple connections when providing an array of connection parameters and the appropriate option to instruct the client about how to aggregate them (clustering, replication or a custom aggregation logic). Named arrays and URI strings can be mixed when providing configurations for each node:

php
$client = new Predis\Client([
    'tcp://10.0.0.1?alias=first-node', ['host' => '10.0.0.2', 'alias' => 'second-node'],
], [
    'cluster' => 'predis',
]);

See the aggregate connections section of this document for more details.

Connections to Redis are lazy meaning that the client connects to a server only if and when needed. While it is recommended to let the client do its own stuff under the hood, there may be times when it is still desired to have control of when the connection is opened or closed: this can easily be achieved by invoking $client->connect() and $client->disconnect(). Please note that the effect of these methods on aggregate connections may differ depending on each specific implementation.

Persistent connections

To increase a performance of your application you may set up a client to use persistent TCP connection, this way client saves a time on socket creation and connection handshake. By default, connection is created on first-command execution and will be automatically closed by GC before the process is being killed. However, if your application is backed by PHP-FPM the processes are idle, and you may set up it to be persistent and reusable across multiple script execution within the same process.

To enable the persistent connection mode you should provide following configuration:

php
// Standalone
$client = new Predis\Client(['persistent' => true]);

// Cluster
$client = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true]]
);

Important

If you operate on multiple clients within the same application, and they communicate with the same resource, by default they will share the same socket (that's the default behaviour of persistent sockets). So in this case you would need to additionally provide a conn_uid identifier for each client, this way each client will create its own socket so the connection context won't be shared across clients. This socket behaviour explained here

php
// Standalone
$client1 = new Predis\Client(['persistent' => true, 'conn_uid' => 'id_1']);
$client2 = new Predis\Client(['persistent' => true, 'conn_uid' => 'id_2']);

// Cluster
$client1 = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true, 'conn_uid' => 'id_1']]
);
$client2 = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true, 'conn_uid' => 'id_2']]
);

Client configuration

Many aspects and behaviors of the client can be configured by passing specific client options to the second argument of Predis\Client::__construct():

php
$client = new Predis\Client($parameters, ['prefix' => 'sample:']);

Options are managed using a mini DI-alike container and their values can be lazily initialized only when needed. The client options supported by default in Predis are:

  • prefix: prefix string applied to every key found in commands.
  • exceptions: whether the client should throw or return responses upon Redis errors.
  • connections: list of connection backends or a connection factory instance.
  • cluster: specifies a cluster backend (predis, redis or callable).
  • replication: specifies a replication backend (predis, sentinel or callable).
  • aggregate: configures the client with a custom aggregate connection (callable).
  • parameters: list of default connection parameters for aggregate connections.
  • commands: specifies a command factory instance to use through the library.
  • readTimeout: (cluster only) Timeout between read operations while loop over connections.

Users can also provide custom options with values or callable objects (for lazy initialization) that are stored in the options container for later use through the library.

Aggregate connections

Aggregate connections are the foundation upon which Predis implements clustering and replication and they are used to group multiple connections to single Redis nodes and hide the specific logic needed to handle them properly depending on the context. Aggregate connections usually require an array of connection parameters along with the appropriate client option when creating a new client instance.

Cluster

Predis can be configured to work in clustering mode with a traditional client-side sharding approach to create a cluster of independent nodes and distribute the keyspace among them. This approach needs some sort of external health monitoring of nodes and requires the keyspace to be rebalanced manually when nodes are added or removed:

php
$parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];
$options    = ['cluster' => 'predis'];

$client = new Predis\Client($parameters);

Along with Redis 3.0, a new supervised and coordinated type of clustering was introduced in the form of redis-cluster. This kind of approach uses a different algorithm to distribute the keyspaces, with Redis nodes coordinating themselves by communicating via a gossip protocol to handle health status, rebalancing, nodes discovery and request redirection. In order to connect to a cluster managed by redis-cluster, the client requires a list of its nodes (not necessarily complete since it will automatically disc

Issues· 25 open

View all issuesOpen on GitHub
  • #1696

    Numbered database support for clusters (Valkey 9+)

    featureUpdated Jul 8, 2026
  • #1147

    RESP simple strings parsing always returns Status object response

    bugUpdated Jul 5, 2026
  • #1146

    Second parameter of lpush should be variable-length argument list

    bugdocumentationUpdated Apr 22, 2026
  • #1565

    Relay compatibility

    relayUpdated Oct 26, 2025
  • #1292

    Improve Relay integration

    featurerelayUpdated Oct 17, 2025
  • #1475

    Support basic events for connection and commands.

    featureUpdated Mar 25, 2025
  • #1460

    Type parameter that are not currently typed

    featureUpdated Mar 18, 2025
  • #923

    Error while iterating on `Predis\Client`: `Object of class Predis\Connection\Aggregate\MasterSlaveReplication could not be converted to string`

    bugUpdated Mar 11, 2025
  • #1037

    Behaviour of Replication::aggregate

    bugUpdated Feb 20, 2025
  • #1507

    MasterSlaveReplication doesn't return back to slave after performing write operation

    bugUpdated Feb 19, 2025

> Tags

PHPphppredisredisredis-cluster

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库