增加雪花算法生成唯一标识文件,并增加测试函数进行生成标识测试

This commit is contained in:
wanglei 2025-10-21 11:09:40 +08:00
parent 9fdf745a3a
commit dcec20c66b
5 changed files with 56 additions and 5 deletions

View File

@ -7,8 +7,7 @@
return {
APP_ENV = "dev", -- dev/prod
locale = 'en',
fallback_locale = 'zh',
locale = 'zh',
time_zone = "+8:00", -- UTC + 8

View File

@ -2,7 +2,7 @@
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by .
--- DateTime: 2025/9/25 08:19
--- 业务逻辑
--- 业务逻辑 对用户数据表进行数据表业务处理
local cjson = require('cjson')
local pgmoon = require('pgmoon')
local dbconf = require("config.database")
@ -10,6 +10,7 @@ local status = require("config.status")
local _M = {}
--获取一个数据库操作连接
local function get_con(cfg)
local code = 0
-- 创建一个新的连接

View File

@ -4,6 +4,12 @@
--- DateTime: 2025/10/15 09:12
---
local calc = require("util.snowalgorithm")
local dataCenterId = 1 -- 根据实际情况配置数据中心 ID 和机器 ID
local machineId = 1 -- 同理配置机器 ID确保在所有机器中唯一且不超过最大值。
local id = calc.generateUuid(dataCenterId, machineId)
print("Generated UUID:", id)
--读取请求体的数据
ngx.req.read_body()

View File

@ -54,7 +54,6 @@ function _M:raw(http_status, http_body)
}
end
function _M:error(http_status, http_headers, http_body)
return {
status = http_status,
@ -63,7 +62,6 @@ function _M:error(http_status, http_headers, http_body)
}
end
function _M:send(response)
ngx.status = response.status
if response.headers ~= nil then

View File

@ -0,0 +1,47 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/21 10:58
--- 雪花算法生成唯一的 ID
--具体使用方法
--local dataCenterId = 1 -- 根据实际情况配置数据中心 ID 和机器 ID
--local machineId = 1 -- 同理配置机器 ID确保在所有机器中唯一且不超过最大值。
--local id = generateUuid(dataCenterId, machineId)
--print("Generated ID:", id)
local _M = {}
local config = {
epoch = 1609459200000, -- 例如2021-01-01 的毫秒时间戳
dataCenterIdBits = 5,
machineIdBits = 5,
sequenceBits = 12, -- 序列号在毫秒内的唯一性
maxDataCenterId = -1 * math.pow(2, dataCenterIdBits),
maxMachineId = -1 * math.pow(2, machineIdBits),
maxSequence = -1 * math.pow(2, sequenceBits)
}
local function calculateOffsets()
local timestampShift = config.sequenceBits + config.machineIdBits + config.dataCenterIdBits
local dataCenterIdShift = config.sequenceBits + config.machineIdBits
local machineIdShift = config.sequenceBits
return {timestampShift = timestampShift, dataCenterIdShift = dataCenterIdShift, machineIdShift = machineIdShift}
end
local function currentTimeMillis()
return math.floor(os.time() * 1000) - config.epoch
end
function _M.generateUuid(dataCenterId, machineId)
local offsets = calculateOffsets()
local timestamp = currentTimeMillis()
local sequence = 0 -- 在实际应用中,你可能需要一个线程安全的序列号生成器来确保同一毫秒内的唯一性。
if sequence > config.maxSequence then return nil end -- 检查序列号是否溢出
local id = bit32.bor(bit32.lshift(timestamp, offsets.timestampShift),
bit32.lshift(dataCenterId, offsets.dataCenterIdShift),
bit32.lshift(machineId, offsets.machineIdShift),
sequence)
return id
end
return _M