我正在编写一个脚本,向我们的应用用户发送可配置的推送通知。我正在使用 amqp gem。我设置了一个测试交换(直接)和绑定到它的单个队列。当我启动脚本时,我看到前几个消息已发布,但之后没有。我不确定我做错了什么,但我认为它与我使用EventMachine api的方式有关。
这是发布JSON格式消息的Rabbit模块/函数。它几乎从各种教程/网站复制/粘贴: 模块Rabbit
# functions needed to communicate with RabbitMQ server
def publish_message_to_direct(server_params, exchange, messages)
begin
AMQP.start(server_params) do |connection|
channel = AMQP::Channel.new(connection)
exchange = channel.direct(exchange,:durable=>true)
messages.each do
|msg|
exchange.publish(msg) do
puts "just published"
connection.close do
puts "connection was closed!"
#EM.stop
end
end
end
end
rescue Exception => e
puts "#{e.message} #{e.backtrace.join("\n")}"
end
nil
end
end
以下是调用发布功能的EM代码:
userids = Array.new
userids.push(1,2,3,12,23,34,56) # this could be any array of integers
EventMachine.run do
exchangeName = 'test.push'
EM.add_periodic_timer(1.0*delay/1000) do
userid = $userids.pop
data = Push.get_push_tokens_for_userid(userid) # we have to query db for tokens
user_notifications = nil
user_notifications = Array.new
data.each_hash do
|row|
begin
notification = Rabbit.create_push_notification_json(
"This is a push notification!",
row['userid'].to_i,
row['token'],
Push.get_device_push_type(row['applicationid'].to_i)
)
user_notifications.push(notification)
pushEvents += 1
rescue Exception => e
puts "#{e.message} #{e.backtrace.join("\n")}"
end
end
if $userids.empty?
EM.stop_event_loop
else
puts "about to publish"
Rabbit.publish_message_to_direct(rmq_params,exchangeName,user_notifications)
userids_pushed.push(userid)
end
end
EM.add_timer(time) do
EM.stop_event_loop
end
Signal.trap("INT") do
EM.stop_event_loop
end
end
输出看起来像这样,一些消息在开始时发布,但在某些时候它们就停止了:
just published
just published
just published
just published
just published
just published
connection was closed!
connection was closed!
connection was closed!
connection was closed!
connection was closed!
connection was closed!
about to publish
just published
connection was closed!
about to publish
just published
just published
just published
connection was closed!
connection was closed!
connection was closed!
about to publish
just published
connection was closed!
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
about to publish
.
.
.
about to publish
老实说,我不知道此时发生了什么。似乎连接几次关闭,然后我假设在某些时候没有重新建立。什么会导致这种行为,我该如何解决?非常感谢任何帮助。