承接 muxtorov98/yii2-kafka 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

muxtorov98/yii2-kafka

Composer 安装命令:

composer require muxtorov98/yii2-kafka

包简介

Kafka integration for Yii2 with full worker auto discovery & retry support.

README 文档

README

Kafka integration for Yii2 with:

  • handler auto-discovery
  • topic + group based worker forking
  • retry on handler failure
  • DLQ publishing for failed messages
  • PSR-3 logger support
  • in-memory metrics counters
  • idempotent handler contract
  • graceful shutdown
  • safer producer flush handling

Package: muxtorov98/yii2-kafka

Requirements

  • PHP ^8.2
  • Yii2 ^2.0
  • ext-rdkafka
  • ext-pcntl

Install

composer require muxtorov98/yii2-kafka

Docker extensions

RUN pecl install rdkafka \
    && docker-php-ext-enable rdkafka \
    && docker-php-ext-install pcntl

Config

Create common/config/kafka.php

<?php

return [
    'brokers' => 'kafka:9092',
    'consumer' => [
        'auto_commit' => true,
        'auto_offset_reset' => 'earliest',
        'max_poll_interval_ms' => 300000,
        'consume_timeout_ms' => 1000,
        'commit_on_failure' => false,
    ],
    'producer' => [
        'acks' => 'all',
        'compression' => 'lz4',
        'linger_ms' => 1,
        'flush_timeout_ms' => 1000,
        'flush_retries' => 3,
    ],
    'retry' => [
        'max_attempts' => 3,
        'backoff_ms' => 500,
    ],
    'dlq' => [
        'enabled' => true,
        'topic_suffix' => '.dlq',
        'include_error_context' => true,
    ],
    'security' => [
        // 'protocol' => 'SASL_SSL',
        // 'sasl' => [
        //     'mechanism' => 'PLAIN',
        //     'username' => 'user',
        //     'password' => 'secret',
        // ],
        // 'ssl' => [
        //     'ca' => '/etc/ssl/certs/ca.pem',
        // ],
    ],
];

Handler example

common/kafka/handlers/OrderCreatedHandler.php

<?php

namespace common\kafka\handlers;

use Muxtorov98\YiiKafka\Attribute\KafkaChannel;
use Muxtorov98\YiiKafka\KafkaHandlerInterface;

#[KafkaChannel(topic: 'order-create', group: 'order-service')]
final class OrderCreatedHandler implements KafkaHandlerInterface
{
    public function handle(array $message): void
    {
        echo 'Order created: ' . json_encode($message, JSON_UNESCAPED_UNICODE) . PHP_EOL;
    }
}

Important:

  • worker only runs handlers matching both topic and group
  • if you want separate consumer groups, define separate handlers with different groups

Idempotent handler example

<?php

namespace common\kafka\handlers;

use Muxtorov98\YiiKafka\Attribute\KafkaChannel;
use Muxtorov98\YiiKafka\IdempotentKafkaHandlerInterface;

#[KafkaChannel(topic: 'order-create', group: 'order-service')]
final class SafeOrderCreatedHandler implements IdempotentKafkaHandlerInterface
{
    public function uniqueKey(array $message): string
    {
        return (string) ($message['order_id'] ?? '');
    }

    public function handle(array $message): void
    {
        // idempotent processing
    }
}

For real production duplicate protection, inject your own persistent store instead of in-memory storage.

Start worker

php yii worker/start

Example output:

🚀 Kafka Worker starting...
👷 Worker started | topic=order-create, group=order-service, PID=721
👂 Kafka listening: topic(s)=order-create, group=order-service

Publish messages

Controller example:

<?php

namespace console\controllers;

use Muxtorov98\YiiKafka\KafkaPublisher;
use yii\console\Controller;

final class KafkaPublishController extends Controller
{
    public function __construct($id, $module, private KafkaPublisher $publisher, $config = [])
    {
        parent::__construct($id, $module, $config);
    }

    public function actionSend(string $topic, string $json): int
    {
        return $this->publisher->publishSend($topic, $json);
    }

    public function actionBatch(string $topic, string $jsonList): int
    {
        return $this->publisher->publishBatch($topic, $jsonList);
    }
}

CLI:

php yii kafka-publish/send order-create '{"order_id":999}'
php yii kafka-publish/batch order-create '[{"id":1},{"id":2}]'

Failure behavior

  • invalid JSON payload in producer throws controlled failure
  • producer checks flush result and throws if delivery is not confirmed in configured attempts
  • handler failures are retried using retry.max_attempts
  • if DLQ is enabled, exhausted failures are published to original-topic.dlq
  • after all retries fail:
    • by default message is not committed
    • if consumer.commit_on_failure = true, message is committed after failure

Observability

Current package supports:

  • PSR-3 logger injection
  • metrics counters:
    • processed_count
    • failed_count
    • retry_count
    • dlq_published_count
    • skipped_duplicate_count
    • consumer_error_count

Default metrics collector is in-memory and logs snapshot through the configured logger.

Custom dependency injection

You can pass custom logger, metrics collector, idempotency store, and producer into Worker.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Muxtorov98\YiiKafka\Metrics\InMemoryMetricsCollector;
use Muxtorov98\YiiKafka\Store\ArrayIdempotencyStore;
use Muxtorov98\YiiKafka\Worker;

$logger = new Logger('kafka');
$logger->pushHandler(new StreamHandler('php://stdout'));

$worker = new Worker(
    $options,
    'order-service',
    ['order-create'],
    $logger,
    new InMemoryMetricsCollector(),
    new ArrayIdempotencyStore()
);

Production notes

  • keep one logical handler per topic + group unless you intentionally want multiple handlers in the same consumer group process
  • use commit_on_failure = false if you prefer redelivery over loss
  • use commit_on_failure = true only if poison messages would block the queue and you accept skipping failed messages
  • use unique groups for independent business flows
  • use persistent idempotency storage if duplicate processing matters
  • use supervisor or systemd to auto-restart workers

Current scope

This package provides a Yii2-focused Kafka worker and producer.

It does not yet provide:

  • Prometheus exporter
  • persistent idempotency storage implementation
  • health endpoint
  • systemd template

If you need framework-agnostic multi-bridge architecture, use the separate universal package instead.

Supervisor example

See:

muxtorov98/yii2-kafka 适用场景与选型建议

muxtorov98/yii2-kafka 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 10 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 muxtorov98/yii2-kafka 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 muxtorov98/yii2-kafka 我们能提供哪些服务?
定制开发 / 二次开发

基于 muxtorov98/yii2-kafka 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-25