php实现发布订阅
发布订阅模式简介
发布订阅(Pub/Sub)是一种消息通信模式,允许发布者将消息发送到频道,订阅者接收来自频道的消息,两者无需直接交互。PHP可通过扩展库或自定义代码实现这一模式。
使用 Redis 实现
Redis 原生支持发布订阅功能,PHP可通过 phpredis 或 predis 扩展库操作:
安装 Redis 扩展(以 phpredis 为例):
pecl install redis
发布者代码示例:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->publish('channel_name', 'Message content');
订阅者代码示例:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->subscribe(['channel_name'], function ($redis, $channel, $message) {
echo "Received: {$message} from {$channel}\n";
});
自定义事件系统
通过 PHP 类和接口实现简单的发布订阅逻辑:
定义事件管理器:
class EventManager {
private $subscribers = [];
public function subscribe(string $event, callable $callback) {
$this->subscribers[$event][] = $callback;
}
public function publish(string $event, $data = null) {
foreach ($this->subscribers[$event] ?? [] as $callback) {
$callback($data);
}
}
}
使用示例:
$eventManager = new EventManager();
$eventManager->subscribe('user_created', function ($user) {
echo "User created: {$user}\n";
});
$eventManager->publish('user_created', 'Alice');
使用消息队列(如 RabbitMQ)
通过 AMQP 扩展实现更复杂的发布订阅场景:
安装 AMQP 扩展:
pecl install amqp
生产者代码:
$connection = new AMQPConnection(['host' => 'localhost']);
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->publish('Message content', 'routing_key');
消费者代码:
$connection = new AMQPConnection(['host' => 'localhost']);
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->bind('exchange_name', 'routing_key');
$queue->consume(function (AMQPEnvelope $envelope) {
echo $envelope->getBody();
});
性能与场景建议
- Redis:适合轻量级、高并发的实时场景。
- 自定义事件:适用于单机应用解耦模块。
- RabbitMQ:需要持久化、复杂路由时使用。
根据实际需求选择方案,注意错误处理与资源释放。







