定制 tourze/symfony-snowflake-bundle 二次开发

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

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

tourze/symfony-snowflake-bundle

Composer 安装命令:

composer require tourze/symfony-snowflake-bundle

包简介

Symfony Bundle for Snowflake ID generation with Redis support

README 文档

README

English | 中文

Packagist

PHP Version

Build Status

Coverage Status

License

Table of Contents

Introduction

A high-performance, distributed Snowflake ID generator bundle for Symfony applications. This bundle implements Twitter's Snowflake algorithm to generate unique, time-ordered, 64-bit IDs for distributed systems. It is designed for scenarios requiring globally unique IDs under high concurrency.

Features

  • Generates 64-bit unique IDs based on godruoyi/php-snowflake library
  • Built-in Redis sequence resolver to ensure uniqueness in high-concurrency environments
  • Auto-generates WorkerId based on hostname for distributed scenario support
  • Zero configuration required for basic usage
  • Fully compatible with Symfony 7.3+
  • Graceful fallback from Redis to RandomSequenceResolver when Redis is unavailable
  • Autowiring support for easy integration with Symfony services
  • Thread-safe ID generation
  • Time-ordered IDs for efficient database indexing

Installation

Requirements

  • PHP >= 8.1
  • Symfony >= 7.3
  • Redis (recommended for distributed sequence safety)

Install via Composer

composer require tourze/symfony-snowflake-bundle

Quick Start

1. Register the Bundle (if not auto-discovered)

Add to config/bundles.php:

return [
    // ...
    Tourze\SnowflakeBundle\SnowflakeBundle::class => ['all' => true],
];

2. Generate a Snowflake ID

Inject the Snowflake service into your service or controller:

<?php

namespace App\Service;

use Tourze\SnowflakeBundle\Service\Snowflake;

class ProductService
{
    public function __construct(
        private readonly Snowflake $snowflake
    ) {
    }

    public function createProduct(): int|string
    {
        // Generate a unique ID for your new product
        $uniqueId = $this->snowflake->id();
        
        // Use the ID in your application logic
        return $uniqueId;
    }
}

Usage

Basic Usage

Simply inject the Snowflake service and call the id() method:

// Inject via constructor
public function __construct(private readonly Snowflake $snowflake) {}

// Generate a unique ID
$id = $this->snowflake->id();

ID Format and Structure

The generated ID is a 64-bit integer with the following structure:

  • 41 bits for timestamp (milliseconds since the epoch or custom epoch)
  • 10 bits for worker ID (machine ID)
  • 12 bits for sequence number (per millisecond counter)

This structure allows for:

  • ~69 years of unique timestamps from custom epoch
  • 1024 different worker IDs
  • 4096 IDs per millisecond per worker

WorkerId Generation

By default, the WorkerId is automatically derived from the hostname using a CRC32 hash modulo operation:

$workerId = crc32(gethostname()) % 32; // Returns a value between 0-31

This ensures different server instances generally get different WorkerIds without manual configuration.

Redis-Based Sequence Resolver

When Redis is available, the bundle automatically uses RedisSequenceResolver for:

  • Enhanced uniqueness guarantees under high concurrency
  • Improved resistance to clock drift
  • Better distribution of IDs across multiple instances

When Redis is unavailable, it gracefully falls back to RandomSequenceResolver to ensure service availability.

Configuration

For basic usage, no extra configuration is required. The bundle works with sensible defaults.

Advanced Usage

Custom Sequence Resolver

For more advanced scenarios, you may extend the ResolverFactory to provide a custom sequence resolver:

<?php

namespace App\Service;

use Godruoyi\Snowflake\SequenceResolver;
use Tourze\SnowflakeBundle\Service\ResolverFactory;

class CustomResolverFactory extends ResolverFactory
{
    public function resolver(): SequenceResolver
    {
        // Your custom resolver implementation
        return new YourCustomSequenceResolver();
    }
}

Then register your custom factory in your service configuration.

Best Practices

  • Redis in Production: Always use Redis in production environments for sequence distribution
  • Clock Synchronization: Ensure your server clocks are synchronized with NTP
  • Worker ID Management: For large distributed deployments, consider implementing a centralized WorkerId assignment mechanism
  • ID Storage: Store Snowflake IDs as BIGINT in databases (or strings if your DB doesn't support 64-bit integers)
  • Benchmarking: Test performance in your environment as high throughput may require tuning

Potential Pitfalls

  • Clock Moving Backwards: If server time moves backward due to NTP adjustments, duplicate IDs might be generated
  • Worker ID Conflicts: In very large deployments, hostname-based WorkerId generation might lead to conflicts
  • Performance without Redis: Without Redis, high concurrency might lead to duplicates under extreme circumstances

Changelog

0.0.x

  • Initial release with Snowflake ID generation support
  • Redis-based sequence resolver with graceful fallback
  • Automatic WorkerId generation based on hostname
  • Full Symfony 7.3+ integration with autowiring support

Contributing

Issues and pull requests are welcome! Please visit the GitHub repository to contribute.

License

This bundle is available under the MIT License. See the LICENSE file for more information.

tourze/symfony-snowflake-bundle 适用场景与选型建议

tourze/symfony-snowflake-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25.11k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 04 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 tourze/symfony-snowflake-bundle 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-20