VOOZH about

URL: https://deepwiki.com/hypervel/redis/4.3-event-system

⇱ Event System | hypervel/redis | DeepWiki


Loading...
Menu

Event System

Purpose and Scope

This document explains the event system implemented in the Hypervel Redis library. The event system dispatches CommandExecuted events for every Redis operation, enabling monitoring, logging, debugging, and performance analysis of Redis commands. This event system integrates with Hyperf's native event dispatcher.

For information about the basic Redis operations that trigger these events, see Basic Operations. For details on how the Redis class manages connections in the context of event dispatching, see Context Management.


Overview

The event system provides observability into all Redis operations executed through the library. Every time a Redis command is invoked via the Redis class, a CommandExecuted event is dispatched containing comprehensive information about the operation, including:

  • Command name and arguments
  • Execution time in milliseconds
  • Connection and pool information
  • Result data or exception details

The event system leverages Hyperf's EventDispatcherInterface to broadcast events, allowing applications to register listeners and react to Redis operations in real-time.

Sources: src/Redis.php1-144


CommandExecuted Event Structure

Event Class

The library uses Hyperf's built-in Hyperf\Redis\Event\CommandExecuted event class. This event is instantiated and dispatched after each Redis command execution, regardless of success or failure.

Event Properties

The CommandExecuted event contains the following information:

PropertyTypeDescription
Command NamestringThe Redis command method name (e.g., 'get', 'set', 'zadd')
ArgumentsarrayThe arguments passed to the command
Execution TimefloatCommand execution duration in milliseconds
ConnectionRedisConnectionThe connection object that executed the command
Pool NamestringThe name of the Redis pool used (e.g., 'default', 'cache')
Resultmixed|nullThe command result if successful, or null if an exception occurred
ExceptionThrowable|nullThe exception object if the command failed, or null if successful

Event Construction

The event is constructed with all properties in the following order:

new CommandExecuted(
 $name, // Command name
 $arguments, // Command arguments
 $time, // Execution time (ms)
 $connection, // RedisConnection instance
 $this->poolName, // Pool name string
 $result ?? null, // Result or null
 $exception ?? null // Exception or null
)

Sources: src/Redis.php7 src/Redis.php43-53


Event Dispatching Mechanism

Timing and Lifecycle

The event dispatching occurs within the __call method of the Redis class, which intercepts all Redis command invocations. The lifecycle follows this pattern:


Implementation Details

The event dispatching logic is implemented in the finally block to ensure events are dispatched regardless of success or failure:

  1. Timing Capture: Before command execution, the start time is captured using microtime(true) src/Redis.php32

  2. Command Execution: The command is executed within a try-catch block src/Redis.php34-40

  3. Error Tracking: If an exception occurs, the $hasError flag is set to true and the exception is re-thrown src/Redis.php38-40

  4. Event Dispatch: In the finally block, execution time is calculated and the event is dispatched src/Redis.php41-53

  5. Connection Management: After event dispatch, the connection is either stored in context or released, depending on the command type src/Redis.php55-75

Execution Time Calculation

The execution time is calculated as the difference between the start time and the current time, rounded to 2 decimal places and expressed in milliseconds:


Sources: src/Redis.php26-78 src/Redis.php32 src/Redis.php42


Event Dispatcher Integration

Dispatcher Retrieval

The event dispatcher is retrieved from the RedisConnection instance, which inherits from Hyperf's base connection class. The dispatcher is accessed via the getEventDispatcher() method:


The null-safe operator (?->) ensures that if no event dispatcher is configured, the code gracefully continues without dispatching events.

Dispatcher Configuration

The event dispatcher is typically configured through Hyperf's dependency injection container. The RedisConnection receives the dispatcher from the framework's configuration during instantiation.

Sources: src/Redis.php43-53


Event Data Flow

The following diagram illustrates how event data flows through the system:


Sources: src/Redis.php26-53


Listening to Events

Registering Event Listeners

To listen to CommandExecuted events in a Hyperf application, register a listener in your application's configuration:

File: config/autoload/listeners.php


Example Listener Implementation

A typical listener implementation receives the CommandExecuted event and processes the data:


Sources: src/Redis.php7 src/Redis.php43-53


Use Cases

Performance Monitoring

The event system enables real-time performance monitoring of Redis operations:

  • Slow Query Detection: Identify commands that exceed performance thresholds
  • Latency Analysis: Track command execution times across different pools
  • Performance Baselines: Establish normal operation metrics and detect anomalies

Logging and Auditing

Events provide comprehensive logging capabilities:

  • Command Logging: Record all Redis operations for audit trails
  • Argument Inspection: Log command arguments for debugging
  • Pool-Specific Logging: Separate logs for different Redis pools (cache, session, etc.)

Error Tracking

Exception information in events facilitates error handling:

  • Error Aggregation: Collect and analyze Redis command failures
  • Alert Systems: Trigger notifications when errors occur
  • Error Rate Monitoring: Track error percentages per command type

Debugging and Development

Events assist in development and troubleshooting:

  • Query Debugging: Inspect exact commands and arguments sent to Redis
  • Connection Tracking: Monitor which connections execute which commands
  • Result Inspection: Verify command results without modifying application logic

Metrics and Analytics

Event data can feed into metrics systems:

  • Command Distribution: Analyze which Redis commands are most frequently used
  • Pool Usage: Track activity across different Redis pools
  • Time-Series Data: Build performance trends over time

Sources: src/Redis.php26-78


Event Guarantees

Always Dispatched

Events are dispatched in a finally block, ensuring they are always sent regardless of:

  • Successful command execution
  • Command exceptions
  • Connection management operations
  • Context storage operations

Exception Handling

When a command throws an exception:

  1. The exception is caught and stored src/Redis.php38-40
  2. The $hasError flag is set to true src/Redis.php39
  3. The event is dispatched with the exception in the finally block src/Redis.php43-53
  4. The exception is re-thrown after event dispatch src/Redis.php40

This ensures that listeners receive notification of failed commands while preserving the exception propagation to the calling code.

Null Results

When an exception occurs, the event's result field is set to null because the $result variable is not assigned in the exception path:


Sources: src/Redis.php41-53 src/Redis.php50


Event Timing Accuracy

Scope of Timing

The execution time measured includes:

  • Command execution on the Redis server
  • Network round-trip time
  • Connection retrieval overhead (if applicable)
  • Transformation overhead in RedisConnection (see Transformation System)

The timing does not include:

  • Event dispatching overhead
  • Connection release operations
  • Context storage operations

Precision

The execution time is calculated with microsecond precision and rounded to 2 decimal places when converted to milliseconds:


This provides millisecond precision with 0.01ms resolution (10 microseconds).

Sources: src/Redis.php32 src/Redis.php42


Integration with Connection Management

Context-Aware Event Dispatching

The event system is aware of connection context management (see Context Management):

  • Events are dispatched regardless of whether the connection comes from context or the pool
  • The same connection object is included in the event whether reused or fresh
  • Connection lifecycle operations (storage/release) occur after event dispatch

Multi-Command Scenarios

For commands that trigger connection persistence (multi, pipeline, select), the event is dispatched before the connection is stored in context:

  1. Command executes
  2. Event is dispatched
  3. Connection is stored in context (if applicable)
  4. Connection is released with defer() (if applicable)

This ensures event listeners receive timely notifications without being delayed by context operations.

Sources: src/Redis.php55-75


Summary

The event system provides comprehensive observability for all Redis operations through the CommandExecuted event. Key characteristics:

  • Universal Coverage: Every Redis command triggers an event
  • Reliable Dispatch: Events are dispatched in finally blocks for guaranteed delivery
  • Rich Context: Events include command details, timing, results, and exceptions
  • Hyperf Integration: Native integration with Hyperf's event dispatcher
  • Performance Data: Millisecond-precision timing for all operations
  • Error Visibility: Exception information included in events

The event system enables robust monitoring, logging, and debugging capabilities without requiring changes to application code that uses the Redis client.

Sources: src/Redis.php1-144