Class: RedisRpc::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_rpc/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, sub_channel, pub_channel, level: Logger::WARN, secret_key: nil, timeout: 10.0) ⇒ Client

Returns a new instance of Client.



13
14
15
16
17
18
19
20
21
22
# File 'lib/redis_rpc/client.rb', line 13

def initialize(url, sub_channel, pub_channel, level: Logger::WARN, secret_key: nil, timeout: 10.0)
  @redis = Redis.new(url: url)
  @sub_channel = sub_channel
  @pub_channel = pub_channel
  @timeout = timeout
  @parser = Parser.new(secret_key)
  @res = Response.new(Redis.new(url: url), pub_channel, init_log(level), @parser)
  @callback = Callback.new(init_log(level))
  exec
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/redis_rpc/client.rb', line 65

def method_missing(m, *args, &block)
  request = {
    method: m,
    params: args,
    uuid: SecureRandom.uuid
  }
  @callback.push(request[:uuid], block) if !block.nil?
  _sync_handler = @res.publish(request, @timeout)
  return block.nil? ? _sync_handler : nil
end

Instance Attribute Details

#handlerObject

Returns the value of attribute handler.



11
12
13
# File 'lib/redis_rpc/client.rb', line 11

def handler
  @handler
end

Instance Method Details

#execObject



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
# File 'lib/redis_rpc/client.rb', line 24

def exec
  @handler = Thread.new do
    begin
      @redis.subscribe(@sub_channel) do |on|
        on.subscribe do |channel, subscriptions|
          @logger.info("Subscribed to ##{channel} (#{subscriptions} subscriptions)")
        end

        on.message do |channel, args|
          @logger.info("##{channel}: #{args}")
          begin
            _args = @parser.parse(args)
            @logger.error(ArgumentError.new("miss method uuid")) and return if _args[:uuid].nil?
            @res.sync_callback(_args, @timeout) if !@callback.exec_callback(_args)
          rescue Exception => e
            @logger.error(e)
          end
        end
        on.unsubscribe do |channel, subscriptions|
          @logger.info("Unsubscribed from ##{channel} (#{subscriptions} subscriptions)")
        end
      end
    rescue Redis::BaseConnectionError => error
      @logger.error("#{error}, retrying in 30s")
      sleep 30
      retry
    end
  end
end

#init_log(level) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/redis_rpc/client.rb', line 54

def init_log(level)
  if defined?(Rails)
    @logger = Rails.logger
  else
    require 'logger'
    @logger = ::Logger.new(STDOUT)
    @logger.level = level
  end
  @logger
end