-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmysqlpool.lua
More file actions
67 lines (60 loc) · 1.39 KB
/
mysqlpool.lua
File metadata and controls
67 lines (60 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
local skynet = require "skynet"
require "skynet.manager"
local mysql = require "mysql"
local CMD = {}
local pool = {}
local maxconn
local index = 2
local function getconn(sync)
local db
if sync then
db = pool[1]
else
db = pool[index]
assert(db)
index = index + 1
if index > maxconn then
index = 2
end
end
return db
end
function CMD.start()
maxconn = tonumber(skynet.getenv("mysql_maxconn")) or 10
assert(maxconn >= 2)
for i = 1, maxconn do
local db = mysql.connect{
host = skynet.getenv("mysql_host"),
port = tonumber(skynet.getenv("mysql_port")),
database = skynet.getenv("mysql_db"),
user = skynet.getenv("mysql_user"),
password = skynet.getenv("mysql_pwd"),
max_packet_size = 1024 * 1024
}
if db then
table.insert(pool, db)
db:query("set charset utf8")
else
skynet.error("mysql connect error")
end
end
end
-- sync为false或者nil,sql为读操作,如果sync为true用于数据变动时同步数据到mysql,sql为写操作
-- 写操作取连接池中的第一个连接进行操作
function CMD.execute(sql, sync)
local db = getconn(sync)
return db:query(sql)
end
function CMD.stop()
for _, db in pairs(pool) do
db:disconnect()
end
pool = {}
end
skynet.start(function()
skynet.dispatch("lua", function(session, source, cmd, ...)
local f = assert(CMD[cmd], cmd .. "not found")
skynet.retpack(f(...))
end)
skynet.register(SERVICE_NAME)
end)