3 Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)
\r
5 Licensed under the Apache License, Version 2.0 (the "License");
\r
6 you may not use this file except in compliance with the License.
\r
7 You may obtain a copy of the License at
\r
9 http://www.apache.org/licenses/LICENSE-2.0
\r
11 Unless required by applicable law or agreed to in writing, software
\r
12 distributed under the License is distributed on an "AS IS" BASIS,
\r
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
14 See the License for the specific language governing permissions and
\r
15 limitations under the License.
\r
20 _M._VERSION = '1.0.0'
\r
22 local tbl_util = require('lib.utils.table_util')
\r
23 local tbl_isempty = tbl_util.isempty
\r
24 local rrcache = require('lib.tools.rr_cache')
\r
26 function _M.select_backserver(servers,svckey)
\r
27 local length = #servers
\r
28 local index = ngx.ctx.last_peer_index
\r
31 --if it is a retry request,use the index in the context as the base
\r
32 index = index%length+1
\r
34 --if it is a normal request,fetch index from cache as the base
\r
35 index = rrcache.get(svckey) or 0
\r
36 index = index%length+1
\r
37 rrcache.set(svckey,index)
\r
39 ngx.ctx.last_peer_index = index
\r
42 local resty_lock = require "resty.lock"
\r
43 local roundrobin_cache = ngx.shared.rr_cache
\r
45 --step1:acquire lock
\r
46 local opts = {["timeout"] = 0.002,["exptime"] = 0.05}--this can be set using the conf file
\r
47 local rrlock = resty_lock:new("rr_locks",opts)
\r
48 local elapsed, err = rrlock:lock(svckey)
\r
50 --return fail("failed to acquire the lock: ", err)
\r
52 --step2:lock successfully acquired!incr the index
\r
53 local index, err = roundrobin_cache:get(svckey)
\r
57 index = index%length+1
\r
59 --step3:update the shm cache with the new index
\r
60 roundrobin_cache:set(svckey,index)
\r
62 --step4:release the lock
\r
63 local ok, err = rrlock:unlock()
\r
65 return servers[index],nil
\r