Compare commits

..

No commits in common. "1ad62eb2524d56b1381844b38c6ca4664b22f663" and "9c564c275afa8874ce1132e31b4e6815aacfe62a" have entirely different histories.

5 changed files with 161 additions and 391 deletions

View File

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

View File

@ -1,146 +1,113 @@
--- ---
--- Generated by EmmyLua(https://github.com/EmmyLua) --- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by . --- Created by .
--- DateTime: 2025/9/25 08:19 --- DateTime: 2025/9/25 08:19
--- 业务逻辑 对用户数据表进行数据表业务处理 --- 业务逻辑
local cjson = require('cjson') local cjson = require('cjson')
local pgmoon = require('pgmoon') local pgmoon = require('pgmoon')
local dbconf = require("config.database") local dbconf = require("config.database")
local status = require("config.status") local status = require("config.status")
local snowflake = require("util.snowflake")
local _M = {}
local _M = {}
local function get_con(cfg)
--获取一个数据库操作连接 local code = 0
local function get_con(cfg) -- 创建一个新的连接
local code = 0 local conn = pgmoon.new(cfg);
-- 创建一个新的连接 ---- 连接到数据库
local conn = pgmoon.new(cfg); local ok, err = conn:connect()
---- 连接到数据库 if not ok then
local ok, err = conn:connect() error("Connection failed: " .. err)
if not ok then code = 0x000002
print("Connection failed: " .. err) end
code = 0x000002 --ngx.say("Connection success")
end return code,conn
--ngx.say("Connection success") end
return code,conn
end -- 查询数据表中的所有用户信息
function _M.getAllUser()
local function getUuid() --组装sql语句
local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间 local sql = "select * from \"T_Users\""
local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间 --获取数据库连接
local snow = snowflake.new(workerId, datacenterId) local code,conn = get_con(dbconf.postgres)
local id = snow:generateUniqueId()-- 生成ID --设置数据库的编码格式
--print("Generated ID:", snow.int64_to_string(id)) --conn:exec("SET NAMES UTF8")
return snow.int64_to_string(id) --执行数据库操作
end local res = conn:query(sql)
if not res then
-- 查询数据表中的所有用户信息 error("Query failed: " .. err)
function _M.getAllUser() code = 0x000003
--组装sql语句 end
local sql = "select * from \"T_Users\"" --整理数据库结果返回值
--获取数据库连接 --for _, row in ipairs(res) do
local code,conn = get_con(dbconf.postgres) -- for key, value in pairs(row) do
--设置数据库的编码格式 -- ngx.say(key .. ":" .. tostring(value))
--conn:exec("SET NAMES UTF8") -- end
--执行数据库操作 --end
local res = conn:query(sql) --关闭数据库
if not res then conn:disconnect()
print("get all users Query failed: "..sql) return code,res
return 0x000003,res end
end
--整理数据库结果返回值 --根据用户id获取用户信息
--for _, row in ipairs(res) do function _M.getUser(id)
-- for key, value in pairs(row) do --组装sql语句
-- ngx.say(key .. ":" .. tostring(value)) local sql = "select * from \"T_Users\" where id="..id
-- end --获取数据库连接
--end local code,conn = get_con(dbconf.postgres)
--关闭数据库 --设置数据库的编码格式
conn:disconnect() --conn:exec("SET NAMES UTF8")
return code,res --执行数据库操作
end local res = conn:query(sql)
if not res then
--根据用户id获取用户信息 error("Query failed: " .. err)
function _M.getUser(id) code = 0x000003
--组装sql语句 end
local sql = "select * from \"T_Users\" where id="..id --关闭数据库
--获取数据库连接 conn:disconnect()
local code,conn = get_con(dbconf.postgres) return code,res
--设置数据库的编码格式 end
--conn:exec("SET NAMES UTF8")
--执行数据库操作 --增加用户信息到数据表
local res = conn:query(sql) function _M.addUser(jsonData)
if not res then --ngx.say(jsonData)
print("Query failed: "..sql) local success, result = pcall(function()
return 0x000003,res return cjson.decode(jsonData)
end end)
--关闭数据库 local res = nil
conn:disconnect() if success == false then
return code,res return 0x000001,res
end end
--组装sql语句
--增加用户信息到数据表 local sql = "select * from \"T_Users\""
function _M.addUser(jsonData) --获取数据库连接
--ngx.say(jsonData) local code,conn = get_con(dbconf.postgres)
local success, result = pcall(function() --执行数据库操作
return cjson.decode(jsonData) res = conn:query(sql)
end) if not res then
local res = nil error("Query failed: " .. err)
if success == false then return 0x000003,res
return 0x000001,res end
end --关闭数据库
--解析json中的键和数据值 conn:disconnect()
local keys = "" return code,res
local values = "" end
for key, value in pairs(result) do
keys = keys..key --增加用户信息到数据表
local val = type(value) function _M.delete_user(id)
if val == "string" then --组装sql语句
values = values.."\'"..value.."\'" local sql = "delete from \"T_Users\" where id="..id
else --获取数据库连接
values = values..value local code,conn = get_con(dbconf.postgres)
end --执行数据库操作
keys = keys.."," local res = conn:query(sql)
values = values.."," if not res then
end error("exec sql failed: " .. err)
--去掉组装最后一位逗号(,) code = 0x000003
--local newKeys = keys:sub(1, #keys -1) end
--local newValues = values:sub(1, #values -1) --关闭数据库
--自己增加对应的uuid数据值 conn:disconnect()
local newKeys = keys.."uuid" return code,res
local uuid = getUuid() end
local newValues = values.."\'"..uuid.."\'"
--组装sql语句 return _M
local sql = string.format("insert into \"T_Users\"(%s)values(%s)", newKeys, newValues)
--ngx.say(sql)
--获取数据库连接
local code,conn = get_con(dbconf.postgres)
--执行数据库操作
res = conn:query(sql)
if not res then
print("adduser sql failed: "..sql)
return 0x000003,res
end
--关闭数据库
conn:disconnect()
return code,res
end
--增加用户信息到数据表
function _M.delete_user(id)
--组装sql语句
local sql = "delete from \"T_Users\" where id="..id
--获取数据库连接
local code,conn = get_con(dbconf.postgres)
--执行数据库操作
local res = conn:query(sql)
if not res then
print("delete exec sql failed: "..sql)
return 0x000003,res
end
--关闭数据库
conn:disconnect()
return code,res
end
return _M

View File

@ -1,52 +1,45 @@
--- ---
--- Generated by EmmyLua(https://github.com/EmmyLua) --- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin. --- Created by admin.
--- DateTime: 2025/10/15 09:12 --- DateTime: 2025/10/15 09:12
--- ---
local snowflake = require("util.snowflake")
--读取请求体的数据
local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间 ngx.req.read_body()
local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间
local snow = snowflake.new(workerId, datacenterId) --获取请求数据
local id = snow:generateUniqueId()-- 生成ID local body_data = ngx.req.get_body_data()
ngx.say("Generated ID:"..snow.int64_to_string(id))
--if not body_data then
--读取请求体的数据 -- ngx.say("read file error:", err)
--ngx.req.read_body() -- return ngx.exit(400)
--end
--获取请求数据 local len = #body_data
--local body_data = ngx.req.get_body_data()
--local file_name = ngx.req.get_body_file()
--if not body_data then ngx.say("file length:", len)
-- ngx.say("read file error:", err)
-- return ngx.exit(400) --ngx.req.read_body_in_buffer(ngx.var.request_body_file)
--end
--local len = #body_data --ngx.say(body_data)
--local file_name = ngx.req.get_body_file()
--ngx.say("file length:", len) --local cjson = require("cjson")
--local file_path = "/home/frankly/work/test.dat"
--ngx.req.read_body_in_buffer(ngx.var.request_body_file) --local file_length = 1024 * 1024 * 400
--local f, err = io.input(file_path, "r")
--ngx.say(body_data) --if not f then
-- ngx.say("read file error:"..err)
-- return
--local cjson = require("cjson") --end
--local file_path = "/home/frankly/work/test.dat" --local content = f:read(file_length) --读取文件内容
--local file_length = 1024 * 1024 * 400 --f:close() --关闭文件
--local f, err = io.input(file_path, "r") ----ngx.say(content)
--if not f then --local res = {
-- ngx.say("read file error:"..err) -- key = "data",
-- return -- value = content
--end --}
--local content = f:read(file_length) --读取文件内容 ----ngx.header["Length"] = #content
--f:close() --关闭文件 --ngx.header["Content-Type"] = 'application/json; charset=UTF-8'
----ngx.say(content) --ngx.say(cjson.encode(res))
--local res = {
-- key = "data",
-- value = content
--}
----ngx.header["Length"] = #content
--ngx.header["Content-Type"] = 'application/json; charset=UTF-8'
--ngx.say(cjson.encode(res))
--ngx.log(ngx.INFO, "send data success") --ngx.log(ngx.INFO, "send data success")

View File

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

View File

@ -1,193 +0,0 @@
local bit = require("bit")
--创建一个雪花算法的类
local snowflake = {}
snowflake.__index = snowflake
local sequence = 0 --序列号
-- 基础配置
local twepoch = 1420041600 -- 时间戳起点2015-01-01
local workerIdBits = 5 -- 机器ID位数
local datacenterIdBits = 5 -- 数据中心ID位数
local timestampBits = 41 -- 时间戳位数
local sequenceBits = 12 -- 序列号位数
local max = math.pow(2, 32) --4294967296
local max_workerId = bit.lshift(1 , workerIdBits) - 1
local max_datacenterId = bit.lshift(1 , datacenterIdBits) - 1
-- 位移偏移量
local timestampShift = sequenceBits + workerIdBits + datacenterIdBits -- 时间戳左移22位
local datacenterIdShift = sequenceBits + datacenterIdBits -- 机器ID左移位数12位
local workerIdShift = sequenceBits -- 数据中心ID左移位数17位
-- 生成序列的掩码这里为4095 (0b111111111111=0xfff=4095)
local sequenceMask = bit.lshift(1, sequenceBits) - 1;
--print("sequenceMask:", sequenceMask)
local lastTimestamp = -1; --上次生成ID的时间戳
--大数据数据左移
local function bit_lshift(x, n)
if n == 0 then return x end
return x * (2 ^ n)
end
--大数据数据右移
local function bit_rshift(x, n)
if n == 0 then return x end
x = x % 2^32 -- 处理负数问题
local res = x / 2^n
return res - res % 1 -- 取整操作,处理小数部分
end
-- 将一个大整数转换为32位整数数组
local function split_into_32bit_chunks(n)
local chunks = {}
while n > 0 do
table.insert(chunks, 1, n % 0x100000000) -- 取32位部分
n = math.floor(n / 0x100000000) -- 移除已处理的32位
end
return chunks
end
-- 执行按位与操作
local function bitwise_and(a, b)
local chunks_a = split_into_32bit_chunks(a)
local chunks_b = split_into_32bit_chunks(b)
local result = 0
local max_len = math.max(#chunks_a, #chunks_b)
print("max_len:", max_len)
for i = 0, max_len do
local chunk_a = chunks_a[i] or 0
local chunk_b = chunks_b[i] or 0
result = result * 0x100000000 + bit.band(chunk_a, chunk_b)
end
return result
end
local function bitwise_or(num1, num2)
local tmp1 = num1
local tmp2 = num2
local str = ""
while (tmp1 ~= 0 or tmp2 ~= 0)
do
local bit1 = tmp1 % 2
local bit2 = tmp2 % 2
if bit1 == 0 and bit2 == 0 then
str = "0" .. str
elseif bit1 == 1 or bit2 == 1 then
str = "1" .. str
else
str = "0" .. str
end
tmp1 = math.modf(tmp1 / 2)
tmp2 = math.modf(tmp2 / 2)
--print("tmp1:", tmp1)
--print("tmp2:", tmp2)
end
return tonumber(str, 2)
end
local function format_number(n, base)
local str = tostring(n)
--print("str:", str)
if base == 16 then -- 十六进制处理示例
return str:gsub("^0[xX]0*", "0x") -- 处理前导零和可能的'0x'
elseif base == 10 then -- 十进制处理示例
--print("value11:", str:gsub("^%-0*", ""))
--return str:gsub("^%-0*", "") -- 处理负数和前导零
return str:gsub("^0*([1-9]%d*)$", "%1")
else -- 其他基数可以按需添加处理逻辑
return str -- 或者根据需要返回其他格式化结果
end
end
function snowflake.int64_to_string(n)
local result = ""
local base = 100000000 -- 选择一个基数例如10^8
while n > 0 do
local part = n % base
result = string.format("%08d", part) .. result
n = math.floor(n / base)
end
local value = format_number(result, 10)
--print("value:", value)
return value
end
--构造函数
function snowflake.new(workerId, datacenterId)
if workerId < 0 then workerId = 0 end
if workerId > max_workerId then workerId = max_workerId end
if datacenterId < 0 then datacenterId = 0 end
if datacenterId > max_datacenterId then datacenterId = max_datacenterId end
local instance = {workerId = workerId, datacenterId = datacenterId}
return setmetatable(instance, snowflake)
end
--获取当前时间戳(毫秒)
function snowflake:getCurrentTimestamp()
local timestamp = os.time()
return timestamp
end
--获取新的时间戳
function snowflake:getNextTimestamp(lastTimestamp)
local timestamp = math.floor(os.time());
while (timestamp <= lastTimestamp)
do
timestamp = math.floor(os.time());
end
return timestamp;
end
-- 雪花算法的实现
function snowflake:generateUniqueId()
--local curtime = os.time()
--print("current time: ", curtime)
local timestamp = self.getCurrentTimestamp() -- 当前时间戳(毫秒)
-- 如果是同一时间生成的,则进行毫秒内序列
if lastTimestamp == timestamp then
sequence = bit.band((sequence + 1), sequenceMask);
-- 毫秒内序列溢出
if sequence == 0 then
--阻塞到下一个毫秒,获得新的时间戳
timestamp = self.getNextTimestamp(lastTimestamp)
end
else
sequence = 0
end
lastTimestamp = timestamp;
--print("sequence:", sequence)
--print("lastTimestamp:", lastTimestamp)
local current_time = lastTimestamp - twepoch
--print("current time: ", current_time)
-- 位运算生成ID
--((timestamp - twepoch) << timestampLeftShift)
local timeNew = bit_lshift(current_time, timestampShift)
--print("timeNew: ", timeNew)
--(datacenterId << datacenterIdShift)
local centerIdNew = bit_lshift(self.datacenterId, datacenterIdShift)
--print("centerIdNew: ", centerIdNew)
--(workerId << workerIdShift)
local workerIdNew = bit_lshift(self.workerId, workerIdShift)
--print("workerIdNew: ", workerIdNew)
--((timestamp - twepoch) << timestampLeftShift)
--| (datacenterId << datacenterIdShift)
--| (workerId << workerIdShift) | sequence
--将相关数据值进行位或操作
local tmp1 = bitwise_or(timeNew, centerIdNew)
local tmp2 = bitwise_or(tmp1, workerIdNew)
local id = bitwise_or(tmp2, sequence)
return id
end
return snowflake
--使用方法示例
--local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间
--local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间
--local test = snowflake.new(workerId, datacenterId)
--local id = test:generateUniqueId()-- 生成ID
--print("Generated ID:", test:int64_to_string(id))