使用 https://github.com/godruoyi/php-snowflake 来生成
<?php
declare(strict_types=1);
use think\facade\Cache;
use think\facade\Config;
use Godruoyi\Snowflake\Snowflake;
use Godruoyi\Snowflake\RedisSequenceResolver;
/**
* 获取redis实例
*
* @return \Redis
*/
function get_redis(): \Redis
{
return Cache::store()->handler();
}
/**
* 生成唯一订单号
*
* @param string $prefix 订单号前缀
* @return string
*/
function build_order_no(string $prefix = ''): string
{
$options = Config::get('cache.stores.redis');
$redis = get_redis();
$snowflake = new Snowflake();
$sequence = new RedisSequenceResolver($redis);
$sequence->setCachePrefix($options['prefix'] . 'order_no:');
$snowflake->setSequenceResolver($sequence);
return $prefix . $snowflake->id();
}
来源:oschina
链接:https://my.oschina.net/u/2266306/blog/4332280