septech-laravel/snowflake

v1.0.3 2020-11-11 08:39 UTC

This package is auto-updated.

Last update: 2024-09-11 17:41:58 UTC


README

安装

composer require septech-laravel/snowflake

# Public config
php artisan vendor:publish --provider="Septech\\Snowflake\\SnowflakeServiceProvider"

环境


# 
SNOWFLAKE_EPOCH="2019-07-01 00:00:00"

用法

use Septech\Snowflake\Facades\Snowflake;

Snowflake::next(); // Alias for id()
Snowflake::id();
Snowflake::parseId('6696174721395998720');

Zookeeper

要使用 Zookeeper,我们需要一个数据库连接来跟踪分配的 ID 和拥有该 ID 的机器。

迁移数据库

# Migrate database schema
php artisan migrate

# Assign the worker id to .env for current marchine.
# It will take the hostname from AWS or get the hostname by gethostname()
php artisan worker:allocate

API

注册路由

// -- routes/api.php
use Septech\Snowflake\Facades\Snowflake;

Snowflake::routes();

将路由包裹在组内

use Septech\Snowflake\Facades\Snowflake;

Route::group(['prefix' => '/snowflake'], function () {
    Snowflake::routes();
});

应用内置中间件

我们提供了一个简单的中间件来保护 API。中间件将从 Authorization 标头获取令牌。或从 $_GET['token'] 或 $_POST['token']。然后与配置中设置的密钥进行比较 snowflake.sever_to_server_tokenenv('SNOWFLAKE_HTTP_TOKEN')。您可以手动设置密钥或运行命令

php artisan worker:token

强制覆盖

php artisan worker:token --force
Route::group(['middleware' => \Septech\Snowflake\Http\Middleware\ServerToken::class], function () {
    Snowflake::routes();
});

使用 Kernel routeMiddleware

// app/Http/Kernel.php
protected $routeMiddleware = [
    // ...
    'server_token' => \Septech\Snowflake\Http\Middleware\ServerToken::class
    // ...
];

// routes/api.php
Route::group(['middleware' => 'server_token'], function () {
    Snowflake::routes();
});