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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| function _M.set(self, key, value, ttl, flags) if type(key) ~= "string" then key = tostring(key) end local node_id = find_key(self, key) local node if not node_id then local free_queue = self.free_queue if queue_is_empty(free_queue) then node = queue_last(self.cache_queue) remove_key(self, self.key_v[node.id]) else node = queue_head(free_queue) end
insert_key(self, key, value, node) else node = self.node_v + node_id self.val_v[node_id] = value end
queue_remove(node) queue_insert_head(self.cache_queue, node)
if ttl then node.expire = ngx_now() + ttl else node.expire = -1 end if type(flags) == "number" and flags >= 0 then node.user_flags = flags else node.user_flags = 0 end end
local function find_key(self, key) local key_hash = hash_string(self, key) return _find_node_in_bucket(key, self.key_v, self.node_v, self.bucket_v[key_hash]) end
local function _find_node_in_bucket(key, key_v, node_v, bucket_hdr_id) if bucket_hdr_id ~= 0 then local prev = 0 local cur = bucket_hdr_id while cur ~= 0 and key_v[cur] ~= key do prev = cur cur = node_v[cur].conflict end if cur ~= 0 then return cur, prev end end end
local function remove_key(self, key) local key_v = self.key_v local val_v = self.val_v local node_v = self.node_v local bucket_v = self.bucket_v
local key_hash = hash_string(self, key) local cur, prev = _find_node_in_bucket(key, key_v, node_v, bucket_v[key_hash])
if cur then key_v[cur] = nil val_v[cur] = nil self.num_items = self.num_items - 1
local next_node = node_v[cur].conflict if prev ~= 0 then node_v[prev].conflict = next_node else bucket_v[key_hash] = next_node end node_v[cur].conflict = 0
return cur end end
local function insert_key(self, key, val, node) local node_id = node.id self.key_v[node_id] = key self.val_v[node_id] = val
local key_hash = hash_string(self, key) local bucket_v = self.bucket_v node.conflict = bucket_v[key_hash] bucket_v[key_hash] = node_id self.num_items = self.num_items + 1 end
|