Skip to content

Instantly share code, notes, and snippets.

@max-did-it
Last active October 22, 2019 09:12
Show Gist options
  • Save max-did-it/43cba6488e7016ec0cca2e662b108a22 to your computer and use it in GitHub Desktop.
Save max-did-it/43cba6488e7016ec0cca2e662b108a22 to your computer and use it in GitHub Desktop.
require 'socket'
class RedisService
attr_accessor :host, :port
LINE = "\r\n"
def initialize(host, port, password: nil)
@host = host
@port = port
@password = password
end
def send(key, val)
open_socket
mes = create_message(key: key, val: val, command: 'set')
send_to_redis(mes)
ensure
close_socket
end
def get(key)
open_socket
mes = create_message(key: key, command: 'get')
send_to_redis(mes)
ensure
close_socket
end
private
def send_to_redis(mes)
if @password
mes = create_message(command: 'auth', val: @password) + mes
end
sleep(1)
@socket.puts(mes)
sleep(1)
response = @socket.read
response.chomp!(LINE)
resp_arr = response.split(LINE)
if @password
return resp_arr[2] if resp_arr[0].eql?('+OK')
return resp_arr[0]
end
resp_arr[1]
end
def create_message(key: nil, val: nil, command: 'set')
arr = []
arr << respialize_string(command)
arr << respialize_string(key) if key
arr << respialize_string(val) if val
"*#{arr.count}" + LINE + arr.join(LINE) + LINE
end
def respialize_string(str, bulk = false)
return "$#{str.to_s.bytesize}#{LINE}+#{str}" if bulk
"$#{str.to_s.bytesize}#{LINE}#{str}"
end
def open_socket
@socket = TCPSocket.open(host, port)
end
def close_socket
@socket && @socket.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment