定制 phpdot/redis 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

phpdot/redis

Composer 安装命令:

composer require phpdot/redis

包简介

Coroutine-safe Redis client wrapping ext-redis with auto-reconnect, exponential backoff, exception translation, and a pool connector for phpdot/pool.

README 文档

README

Coroutine-safe Redis client for PHP 8.4+. Wraps ext-redis \Redis with auto-reconnect, exponential backoff, exception translation, and a pool connector for phpdot/pool.

One RedisConnection owns one \Redis socket. Under Swoole, borrow a connection per coroutine through a pool so no two coroutines ever interleave commands on one socket — the same pattern phpdot/mongodb uses.

Table of Contents

Install

composer require phpdot/redis

Requires PHP 8.4+, ext-redis ^6.0, and phpdot/contracts ^1.4.

Quick Start

use PHPdot\Redis\Config\RedisConfig;
use PHPdot\Redis\RedisConnection;

$connection = new RedisConnection(new RedisConfig(
    host: '127.0.0.1',
    port: 6379,
    password: 'secret',
    database: 0,
));
$connection->connect();

// Reach the underlying \Redis for commands
$connection->getClient()->set('hello', 'world');
$connection->getClient()->get('hello'); // 'world'

$connection->close();

Architecture

RedisConfig (readonly value object)
        │
        ▼
RedisConnection ── getClient() ──► \Redis  (ext-redis)
        ▲
        │ owns lifecycle
RedisConnector ──implements──► PHPdot\Contracts\Pool\ConnectorInterface
  • RedisConfig — immutable connection parameters (#[Config('redis')]).
  • RedisConnection — lifecycle + the raw \Redis seam. Mirrors phpdot/mongodb's MongoConnection.
  • RedisConnector — adapts RedisConnection to the pool contract. Mirrors MongoConnector. Depends only on phpdot/contracts, so the package works without phpdot/pool (FPM, CLI, scripts).

RedisConnection

RedisConfig

new RedisConfig(
    host: '127.0.0.1',     // TCP host (ignored when path is set)
    port: 6379,            // TCP port (ignored when path is set)
    path: '',              // Unix socket path; supersedes host/port when set
    password: '',          // AUTH password (Redis 5-). Empty skips AUTH.
    username: '',          // ACL username (Redis 6+). Empty = password-only AUTH.
    database: 0,           // SELECT index after connect
    timeout: 0.0,          // connect timeout, seconds (0 = unlimited)
    retryInterval: 0,      // ext-redis reconnect delay, ms
    readTimeout: 0.0,      // read timeout, seconds
    tls: false,            // connect over TLS (prefixes host with tls://)
    ssl: [],               // stream SSL context options (CA, cert, verify…)
    maxRetries: 3,         // connect-attempt retries, exponential backoff
    persistent: false,     // use pconnect (off by default — pool owns lifecycle)
    context: [],           // catch-all passed as ext-redis' $context arg
);

Lifecycle

$connection->connect();          // establish + AUTH + SELECT + PING
$connection->isConnected();      // local flag, no server round-trip
$connection->ping();             // round-trip PING → bool
$connection->ensureConnected();  // throws ConnectionException if down
$connection->reconnect();        // close() then connect()
$connection->close();            // idempotent
$connection->getConfig();        // RedisConfig
$connection->getClient();        // \Redis (throws if not connected)

Resilience

connect() retries up to maxRetries times with exponential backoff (100ms → 200ms → 400ms…). AUTH failures (NOAUTH, WRONGPASS) throw AuthenticationException immediately and are not retried. All other connection failures accumulate and throw ConnectionException once the retry budget is exhausted.

Coroutine Safety

ext-redis commands are blocking socket I/O. Two coroutines sharing one \Redis interleave request/reply bytes and corrupt each other — this is the footgun phpdot/redis-ql's own docs warn about.

phpdot/redis makes the safe pattern trivial: pool connections, borrow one per coroutine. Each pooled RedisConnection wraps exactly one \Redis; a coroutine borrows it, runs commands via getClient(), and returns it. No socket is ever shared across concurrent coroutines.

Connection Pooling

RedisConnector implements PHPdot\Contracts\Pool\ConnectorInterface, so phpdot/pool can hold and manage RedisConnection instances:

use PHPdot\Pool\Pool;
use PHPdot\Pool\PoolConfig;
use PHPdot\Redis\Config\RedisConfig;
use PHPdot\Redis\RedisConnector;

$pool = new Pool(
    new RedisConnector(new RedisConfig()),
    PoolConfig::default(),
);

// Borrow a connection per coroutine
$connection = $pool->borrow();
try {
    $connection->getClient()->set('key', 'value');
} finally {
    $pool->release($connection);
}

The connector depends only on phpdot/contractsphpdot/pool is not a runtime requirement, so the package stays usable in non-pooled runtimes (FPM, CLI one-shots).

Exception Handling

RedisException (extends RuntimeException)
├── ConnectionException        // connect failure after retries; carries getHost()
└── AuthenticationException    // AUTH / ACL denial

RedisException from ext-redis is caught and translated inside connect(); RedisConnection's own methods throw PHPdot\Redis\Exception\* types only.

use PHPdot\Redis\Exception\AuthenticationException;
use PHPdot\Redis\Exception\ConnectionException;

try {
    $connection->connect();
} catch (AuthenticationException $e) {
    // bad credentials — do not retry
} catch (ConnectionException $e) {
    // unreachable after retries; $e->getHost() tells you which endpoint
}

Escape Hatch

getClient(): \Redis returns the underlying ext-redis instance for any command the wrapper does not surface. This is the primary consumer seam — phpdot/cache's RedisDriver, phpdot/session's RedisHandler, and phpdot/redis-ql's PhpRedisClient can all receive a pooled \Redis through it.

API Reference

RedisConfig API

Method Returns Notes
connectHost() string socket path or tls://-prefixed host
buildContext() ?array merged stream/SSL context, or null
getHostString() string socket path or host:port for errors

RedisConnection API

Method Returns Throws
connect() void ConnectionException, AuthenticationException
close() void never
isConnected() bool never
ping() bool never
ensureConnected() void ConnectionException
reconnect() void ConnectionException, AuthenticationException
getClient() \Redis ConnectionException
getConfig() RedisConfig never

RedisConnector API

Implements PHPdot\Contracts\Pool\ConnectorInterface.

Method Returns Notes
connect() object fresh connected RedisConnection
isAlive(object) bool type-guarded + ping()
close(object) void type-guarded, never throws

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-07-06

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固