Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local serpent = require'serpent'
- local socket = require'socket'
- local connection = {}
- connection.__index = connection
- connection.default = {timeout = 5, ip = '127.0.0.1', port = 6379}
- connection.protocol = socket.tcp4 or socket.tcp
- function connection:new(ip, port, timeout)
- local o = {}
- o.ip = ip or self.default.ip
- o.port = port or self.default.port
- o.timeout = timeout or self.default.timeout
- return setmetatable(o, self)
- end
- function connection:connect()
- if self.tcp then return true end
- self.tcp = self.protocol()
- self.tcp:connect(self.ip, self.port)
- self.tcp:settimeout(self.timeout)
- self.tcp:send'PING\n'
- if self.tcp:receive'*l' == '+PONG' then return true end
- self:disconnect()
- return false, 'redis not responded'
- end
- function connection:disconnect()
- if not self.tcp then return end
- self.tcp:close()
- self.tcp = nil
- end
- local cr = {}
- connection.receiver = cr
- -- simple strings
- cr['+'] = function(self, data) return data end
- -- errors
- cr['-'] = function(self, data) return false, data end
- -- bulk strings
- cr['$'] = function(self, data)
- local bytes = tonumber(data)
- if not bytes or bytes < 1 then return bytes end
- local res, err = self.tcp:receive(bytes + 2) -- data + \r\n
- return err and false or res:sub(1, -3), err -- cut \r\n
- end
- -- integers
- cr[':'] = function(self, data)
- return tonumber(data)
- end
- -- arrays
- cr['*'] = function(self, data)
- local count = tonumber(data)
- if not count then return false, 'I can\'t help ((' end
- local list = {}
- for i = 1, count do
- list[i] = self:receive()
- end
- return list
- end
- function connection:receive()
- local res, err = self.tcp:receive'*l'
- if not res then return self.disconnect(), err end
- local head, tail = res:sub(1, 1), res:sub(2)
- return self.receiver[head](self, tail)
- end
- function connection:request(command, close)
- if not self:connect() then return end
- self.tcp:send(command..'\r\n')
- return self:receive()
- end
- if not ... then
- c = connection:new()
- local test_case = {
- 'keys home*',
- 'type home:1',
- 'hgetall home:id1',
- 'get home:1'
- }
- for i, v in ipairs(test_case) do
- local res, err = c:request(v)
- local tp = type(res)
- if not res then res = '--ERROR '..tostring(err) end
- res = type(res) == 'table' and serpent.block(res) or tostring(res)
- print('REQUEST ['..v..'] : ('..tp..') '..res)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement