Class: Nsq::Producer

Inherits:
ClientBase show all
Defined in:
lib/nsq/producer.rb

Instance Attribute Summary collapse

Attributes inherited from ClientBase

#connections

Instance Method Summary collapse

Methods inherited from ClientBase

#connected?, #terminate

Methods included from AttributeLogger

included

Constructor Details

#initialize(opts = {}) ⇒ Producer

Returns a new instance of Producer.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/nsq/producer.rb', line 7

def initialize(opts = {})
  @connections = {}
  @topic = opts[:topic] || raise(ArgumentError, 'topic is required')
  @discovery_interval = opts[:discovery_interval] || 60

  nsqlookupds = []
  if opts[:nsqlookupd]
    nsqlookupds = [opts[:nsqlookupd]].flatten
    discover_repeatedly(
      nsqlookupds: nsqlookupds,
      interval: @discovery_interval
    )

  elsif opts[:nsqd]
    nsqds = [opts[:nsqd]].flatten
    nsqds.each{|d| add_connection(d)}

  else
    add_connection('127.0.0.1:4150')
  end

  at_exit{terminate}
end

Instance Attribute Details

#topicObject (readonly)

Returns the value of attribute topic.



5
6
7
# File 'lib/nsq/producer.rb', line 5

def topic
  @topic
end

Instance Method Details

#write(*raw_messages) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nsq/producer.rb', line 32

def write(*raw_messages)
  # stringify the messages
  messages = raw_messages.map(&:to_s)

  # get a suitable connection to write to
  connection = connection_for_write

  if messages.length > 1
    connection.mpub(@topic, messages)
  else
    connection.pub(@topic, messages.first)
  end
end