【问题标题】:sidekiq workers sending twilio calls in wrong ordersidekiq 工作人员以错误的顺序发送 twilio 呼叫
【发布时间】: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


    【解决方案1】:

    如果您要发送多条消息,则每条消息都会通过自己的路线到达目标运营商。即使它们以正确的顺序发送,也不能保证手机会以正确的顺序接收它们。克服此问题的一种方法是使用最多 1600 个字符的串联消息(在美国)。如果您通过 Messages 资源发送一条长消息,它将作为一条长消息接收。只需确保您使用的是 Messages 资源:

    @client.account.messages.create()

    而不是

    client.account.sms.messages.create()

    您可以在这里阅读更多内容:

    https://www.twilio.com/help/faq/sms/does-twilio-support-concatenated-sms-messages-or-messages-over-160-characters

    http://twilio-ruby.readthedocs.org/en/latest/usage/messages.html

    【讨论】:

    • 拍摄...我应该更清楚...消息没有以正确的顺序保存到我的数据库中
    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多