Class: RedisRpc::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(url, sub_channel, pub_channel, level: Logger::WARN) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
16
17
18
19
# File 'lib/redis_rpc/client.rb', line 11

def initialize(url, sub_channel, pub_channel, level: Logger::WARN)
  @redis = Redis.new(url: url)
  @sub_channel = sub_channel
  @pub_channel = pub_channel
  @res = Response.new(Redis.new(url: url), pub_channel)
  @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
# 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)
  @res.publish(request)
end

Instance Method Details

#execObject



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

def exec
  @thread = Thread.new do
    begin
      @redis.subscribe(@sub_channel, RedisRpc::EXCEPTION_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}")
          case channel.to_sym
          when RedisRpc::EXCEPTION_CHANNEL
            @logger.error("exception: #{args}")
          else
            begin
              @callback.exec_callback(args)
            rescue Exception => e
              @logger.error(e.message.to_s)
            end
          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