Class: SensorsAnalytics::BatchConsumer

Inherits:
SensorsAnalyticsConsumer show all
Defined in:
lib/sensors_analytics/consumers.rb

Overview

实现批量、同步发送的 Consumer,初始化参数为 Sensors Analytics 收集数据的 URI 和批量发送的缓存大小

Constant Summary collapse

MAX_FLUSH_BULK =
50

Instance Method Summary collapse

Methods inherited from SensorsAnalyticsConsumer

#request!

Constructor Details

#initialize(server_url, flush_bulk = MAX_FLUSH_BULK) ⇒ BatchConsumer

Returns a new instance of BatchConsumer.



56
57
58
59
60
# File 'lib/sensors_analytics/consumers.rb', line 56

def initialize(server_url, flush_bulk = MAX_FLUSH_BULK)
  @event_buffer = []
  @flush_bulk = [flush_bulk, MAX_FLUSH_BULK].min
  super(server_url)
end

Instance Method Details

#flushObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/sensors_analytics/consumers.rb', line 67

def flush
  @event_buffer.each_slice(@flush_bulk) do |event_list|
    begin
      response_code, response_body = request!(event_list)
    rescue => e
      raise ConnectionError.new("Could not connect to Sensors Analytics, with error \"#{e.message}\".")
    end

    unless response_code.to_i == 200
      raise ServerError.new("Could not write to Sensors Analytics, server responded with #{response_code} returning: '#{response_body}'")
    end
  end
  @event_buffer = []
end

#send(event) ⇒ Object



62
63
64
65
# File 'lib/sensors_analytics/consumers.rb', line 62

def send(event)
  @event_buffer << event
  flush if @event_buffer.length >= @flush_bulk
end