urfysoft/transactional-outbox 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

urfysoft/transactional-outbox

Composer 安装命令:

composer require urfysoft/transactional-outbox

包简介

Implements the Transactional Outbox pattern for Laravel, ensuring reliable event publishing by storing messages in an outbox table within the same database transaction.

README 文档

README

Complete Transactional Outbox implementation for reliable communication between microservices.

Installation

composer require urfysoft/transactional-outbox

Publish assets

# Publish config and migrations
php artisan vendor:publish --provider="Urfysoft\TransactionalOutbox\TransactionalOutboxServiceProvider"

This command copies:

  • config/transactional-outbox.php
  • database/migrations/*create_outbox_messages_table.php
  • database/migrations/*create_inbox_messages_table.php

Run the migrations after publishing:

php artisan migrate

Configuration

Key settings live in config/transactional-outbox.php.

  • Service identity & Sanctum ability
    • service_name: name announced in outbound headers.
    • sanctum.required_ability: ability that incoming Sanctum tokens must possess.
  • Headers
    • Override header names or the prefix (default X-) via the headers array.
  • Destinations
    • Map logical service names to endpoints inside the services array.
  • Driver
    • Choose the message broker driver (http, kafka, rabbitmq when implemented).
  • Processing
    • Control batch size, retry limits, and throttling.
  • Inbox handlers
    • Register classes implementing Urfysoft\TransactionalOutbox\Contracts\InboxEventHandler under inbox.handlers.

Example handler:

namespace App\Messaging;

use Urfysoft\TransactionalOutbox\Contracts\InboxEventHandler;
use Urfysoft\TransactionalOutbox\Models\InboxMessage;

class PaymentCompletedHandler implements InboxEventHandler
{
    public function eventType(): string
    {
        return 'PaymentCompleted';
    }

    public function handle(InboxMessage $message): void
    {
        // process payload...
    }
}

Register the class in config/transactional-outbox.php or at runtime:

use TransactionalOutbox;
use App\Messaging\PaymentCompletedHandler;

TransactionalOutbox::registerInboxHandler(new PaymentCompletedHandler());

Sanctum setup

The package expects Laravel Sanctum to be installed and configured.

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Issue tokens for upstream services with the configured ability (default transactional-outbox):

$serviceUser->createToken('microservice:inventory', ['transactional-outbox']);

Architecture Overview

Outbox Pattern (Sending Messages)

  1. Business logic and an outbox message are persisted in the same database transaction
  2. A background worker reads the outbox table and publishes to the message broker
  3. Messages are marked as published once delivery succeeds
  4. Failed messages are automatically retried

Inbox Pattern (Receiving Messages)

  1. Messages arrive via HTTP webhooks or a broker consumer
  2. Each message is stored in the inbox table for idempotency (duplicate detection)
  3. A background worker processes inbox messages
  4. Business logic runs in a transaction that also updates the message status

Usage Examples

Sending Messages to Other Services

Single destination

use App\Services\OutboxService;

class OrderController extends Controller
{
    public function __construct(private OutboxService $outbox) {}
    
    public function createOrder(Request $request)
    {
        $order = $this->outbox->executeAndSend(
            businessLogic: fn() => Order::create($request->all()),
            destinationService: 'payment-service',
            eventType: 'OrderCreated',
            payload: ['order_id' => $orderId, ...],
            aggregateType: 'Order',
            aggregateId: $orderId
        );
        
        return response()->json($order, 201);
    }
}

Multiple destinations

$order = $this->outbox->executeAndSendMultiple(
    businessLogic: fn() => $order->complete(),
    messages: [
        [
            'destination_service' => 'inventory-service',
            'event_type' => 'OrderCompleted',
            'payload' => [...],
            'aggregate_type' => 'Order',
            'aggregate_id' => $orderId,
        ],
        [
            'destination_service' => 'notification-service',
            'event_type' => 'OrderCompleted',
            'payload' => [...],
            'aggregate_type' => 'Order',
            'aggregate_id' => $orderId,
        ],
    ]
);

Receiving Messages from Other Services

Event handler registration

Inside MessageBrokerServiceProvider:

$processor->registerHandler('PaymentCompleted', function ($message) {
    $order = Order::find($message->payload['order_id']);
    $order->update(['payment_status' => 'paid']);
});

Webhook endpoint

Other services POST to:

POST https://your-service/api/webhooks/messages
Headers:
  X-Message-Id: unique-id
  X-Source-Service: payment-service
  X-Event-Type: PaymentCompleted
  X-API-Key: your-key
Body: {...payload...}

Message Broker Options

HTTP (Default)

  • Simple REST API calls
  • No additional infrastructure required
  • Great for small/medium deployments

Kafka

composer require nmred/kafka-php

Set MESSAGE_BROKER_DRIVER=kafka

RabbitMQ

composer require php-amqplib/php-amqplib

Set MESSAGE_BROKER_DRIVER=rabbitmq

Running the System

Start the scheduler (required)

php artisan schedule:work

Manual processing

# Process outbox messages
php artisan outbox:process

# Process inbox messages
php artisan inbox:process

# Process messages for a specific service
php artisan outbox:process --service=payment-service

# Retry failed messages
php artisan outbox:process --retry
php artisan inbox:process --retry

# Cleanup old messages
php artisan messages:cleanup --days=7

Configuration Tips

  • Header names: customize transactional-outbox.headers to redefine which headers carry the message id, source service, event type, or to change the prefix used when collecting custom metadata.
  • Inbox handlers: list handler classes inside transactional-outbox.inbox.handlers. Each class must implement Urfysoft\TransactionalOutbox\Contracts\InboxEventHandler (define eventType() and handle()).
  • Runtime registration: handlers can also be registered anywhere via the facade:
use TransactionalOutbox;
use App\Messaging\PaymentCompletedHandler;

TransactionalOutbox::registerInboxHandler(new PaymentCompletedHandler());

Monitoring

-- Pending outbox messages
SELECT * FROM outbox_messages WHERE status = 'pending';

-- Failed outbox messages
SELECT * FROM outbox_messages WHERE status = 'failed';

-- Pending inbox messages
SELECT * FROM inbox_messages WHERE status = 'pending';

Key Capabilities

Atomicity: Business logic and messages live in the same transaction
Reliability: No data loss even when the broker is down
Idempotency: Duplicate messages are automatically detected
Retry logic: Failed deliveries are retried automatically
Multi-broker: HTTP, Kafka, RabbitMQ drivers
Monitoring: Track message statuses and errors
Scalability: Batch processing support

Best Practices

  1. Always propagate a correlation ID for request tracing
  2. Keep payloads small—send references instead of full objects
  3. Monitor failed messages and set up alerts
  4. Clean up regularly to remove processed records
  5. Test idempotency to ensure handlers tolerate duplicates
  6. Use a dead-letter queue after exhausting retries
  7. Version your events—include a version in event_type

Troubleshooting

Messages are not processed:

  • Ensure the scheduler is running: php artisan schedule:work
  • Inspect message statuses in the database
  • Check logs: tail -f storage/logs/laravel.log

Duplicate messages:

  • The Inbox pattern handles duplicates automatically
  • Verify message_id uniqueness

Failed messages:

  • Inspect the last_error column
  • Use the retry command: php artisan outbox:process --retry
  • Confirm the destination service is reachable

Advanced Topic: Saga Pattern

Combine Transactional Outbox with the Saga pattern for distributed transactions:

// Orchestration-based saga
class OrderSaga
{
    public function execute(Order $order)
    {
        DB::transaction(function () use ($order) {
            // Step 1: Reserve inventory
            $this->outbox->sendToService(...);
            
            // Step 2: Charge payment
            $this->outbox->sendToService(...);
            
            // Step 3: Confirm the order
            $this->outbox->sendToService(...);
        });
    }
    
    // Compensation handlers for failures
    public function compensate() { ... }
}

urfysoft/transactional-outbox 适用场景与选型建议

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

它主要适用于以下技术方向: 「laravel」 「outbox」 「transactional-outbox」 「Urfysoft」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 urfysoft/transactional-outbox 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-15