【发布时间】:2014-06-22 11:46:27
【问题描述】:
我有一个 SMS 应用程序,它将 SMS 消息发送到 sidekiq 工作人员,然后 ping twilio 以实际发送消息。我遇到的问题是,通过将消息发送给工作人员,有时超过 160 个字符的消息会以错误的顺序发送。我认为这是因为 sidekiq 正在同时运行这些作业。我该如何解决这个问题?
以前,我会循环遍历消息的每 160 个字符,并将每 160 个字符的字符串发送给要发送的工作人员。这会导致问题,因为工作人员会在消息出现故障时同时进行设置和运行。为了解决这个问题,我将 160 个字符的逻辑移到了 worker 中,我相信这解决了单个消息的问题。
但是,如果在 1-2 秒内收到多条消息,它们会同时发送,因此可能会再次出现故障。如何确保 sidekiq 按我调用 perform_async 方法的顺序处理消息?这是我的代码:
//messages_controller.rb
SendSMSWorker.new.perform(customer.id, message_text, 'sent', false, true)
//send_sms_worker.rb
def perform(customer_id, message_text, direction, viewed, via_api)
customer = Customer.find(customer_id)
company = customer.company
texts = message_text.scan(/.{1,160}/) # split the messages up into 160 char pieces
texts.each do |text|
message = customer.messages.new(
user_id: company.admin.id, # set the user_id to the admin's ID when using the api
company_id: company.id,
text: text,
direction: 'sent',
viewed: false,
via_api: true
)
# send_sms returns nil if successful
if error = message.send_sms
customer.mark_as_invalid! if error.code == 21211
else
# only save the message if the SMS was successfully sent
puts "API_SEND_MESSAGE company_id: #{company.id}, customer_id: #{customer.id}, message_id: #{message.id}, texts_count: #{texts.count}"
message.save
Helper.publish(company.admin, message.create_json_with_extra_attributes(true))
end
end
end
需要明确的是,message.send_sms 是消息模型上实际通过 twilio 发送短信的方法。谢谢!
【问题讨论】:
标签: ruby-on-rails twilio sidekiq