mucts/laravel-snowflake

雪花算法:分布式环境,生成全局唯一的订单号

1.4.2 2020-05-24 17:15 UTC

This package is auto-updated.

Last update: 2024-09-29 05:48:47 UTC


README

Build Status Code Intelligence Status Scrutinizer Code Quality Total Downloads Latest Stable Version License

Laravel Snowflake

此Laravel包用于生成类似于Twitter中的雪花算法的64位标识符。

安装

服务器要求

请确保您的服务器满足以下要求

  • php ^7.4
  • JSON PHP 扩展
  • OpenSSL PHP 扩展
  • GMP PHP 扩展
  • BCMath PHP 扩展
  • laravel/framework ^7.0

Laravel 安装

composer require mucts/laravel-snowflake

使用方法

生成雪花标识符

$id = Snowflake::next();

分析雪花标识符

$info = Snowflake::info($id);

与 Eloquent 的使用

MuCTS\LaravelSnowflake\Models\Traits\Snowflake 特性添加到您的 Eloquent 模型中。此特性将主键的类型设置为 snowflake。特性会自动将 $incrementing 属性设置为 false。

<?php
namespace App;

use MuCTS\LaravelSnowflake\Models\Traits\Snowflake;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Snowflake, Notifiable;
}

最后,在迁移中,将主键设置为 bigIntegerunsignedprimary

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        // $table->increments('id');
        $table->bigInteger('id')->unsigned()->primary();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

配置

如果不存在 config/snowflake.php,请运行以下命令:

php artisan vendor:publish