以下代码,实现的业务逻辑:
1、oonum在0~49之间使用10.253.94.7上数据库
1.1、若10.253.94.7挂了,则使用10.253.94.8
2、oonum在50~99之间使用10.253.94.8上数据库
2.1、若10.253.94.8挂了,则使用10.253.94.7
我看了一些你们之前讨论的帖子,好像是不是说一个mysql:new()的只能一个连接?
- local mysql = require 'resty.mysql'
- local db,err = mysql:new()
-
- if not db then
- ngx.log(ngx.ERR, 'failed to instantiate mysql:', err)
- ngx.say('{"result":"false","code":"3"}')
- return
- end
-
- db:set_timeout(1000) -- 1 sec
- if (oonum<50 and oonum>=0) then
- ngx.log(ngx.INFO, 'oo between 0-49')
- ok,err,errno,sqlstate = db:connect{
- host = '10.253.94.7',
- port = 3306,
- database = 'user_scores',
- user = 'scores',
- password = 'ali88',
- max_packet_size = 1024*1024
- }
-
- if not ok then
- ngx.log(ngx.ERR,'failed to connect to db1:',err,':',errno,' ',sqlstate)
- ok,err,errno,sqlstate = db:connect {
- host = '10.253.94.8',
- port = 3306,
- database = 'user_scores',
- user = 'scores',
- password = 'ali88',
- max_packet_size = 1024*1024
- }
- if not ok then
- ngx.log(ngx.ERR,'failed to connect to db2:',err,':',errno,' ',sqlstate)
- ngx.say('{"result":"false","code":"4"}')
- return
- end
- end
-
- end
-
- if (oonum>=50 and oonum<=99) then
- ngx.log(ngx.INFO, 'oo between 50-99')
- ok,err,errno,sqlstate = db:connect{
- host = '10.253.94.8',
- port = 3306,
- database = 'user_scores',
- user = 'scores',
- password = 'ali88',
- max_packet_size = 1024*1024
- }
-
- if not ok then
- ngx.log(ngx.ERR,'failed to connect to db1:',err,':',errno,' ',sqlstate)
- ok,err,errno,sqlstate = db:connect {
- host = '10.253.94.7',
- port = 3306,
- database = 'user_scores',
- user = 'scores',
- password = 'ali88',
- max_packet_size = 1024*1024
- }
- if not ok then
- ngx.log(ngx.ERR,'failed to connect to db2:',err,':',errno,' ',sqlstate)
- ngx.say('{"result":"false","code":"5"}')
- return
- end
- end
-
- end
...do something...
local ok, err = db:set_keepalive(0,200)