Rails 线程安全变量

Rails thread secure variables

我遇到了有关线程安全变量的问题。我有一个控制器方法,可以将短信发送到给定的号码。但是,如果用户同时发出请求,变量将被覆盖。
我知道 RoR 不是线程安全的,我必须做到这一点,但我无法通过实时响应做到这一点。如果我从用户那里获取所有数据并在后台工作中进行,那会更容易。

例如,假设第一个用户尝试向 x 号码发送内容为 a 的短信,第二个用户尝试向 y 号码发送内容为 b 的短信。如果他们在完全相同的时刻发出请求,x 号会收到两条内容为 a 和 b 的短信。

def create
  success = false
  message = nil
  status  = 422
  if params[:receivers].present? && params[:title].present? && params[:content].present?
    if params[:is_future_sms].present? && params[:is_future_sms].to_s == 'true' && !params[:send_date].present?
      render json: {success: false, message: 'Insufficient Parameter'}
    else
      sms = @account.sms_objects.new(sms_object_params)
      sms.sms_title_id = set_sms_title_id
      sms.receivers = sms.receivers.to_s
      receivers = NumberOperations.sanitize_receivers_with_hash(sms.receivers)
      if receivers.count > 0
        total_count = sms.credit(sms.content)
        sms_balance = sms.balance(sms.content)
        receivers.map{|r| r[:balance] = sms_balance}
        sms_balance = receivers.count * total_count

        if @account.can_afford_sms?(sms_balance)
          if sms.save
            SendSmsJob.perform_later(sms.id, receivers)
            success = true
            message = 'Messages created successfully'
            status  = 201
          else
            success = false
            message = sms.errors.full_messages.to_sentence
            status  = 422
          end
        else
          success = false
          message = 'Insufficient Credit'
          status  = 422
        end
      else
        success = false
        message = 'No valid number'
        status  = 422
      end
    end
  else
    success = false
    message = 'Insufficient Parameter'
    status  = 422
  end
  render json: { success: success, message: message }, status: status
end

我想我可以用 mutex 和 Thread.new 解决问题,但是当我使用它时它没有给用户响应。

def create
  th = Thread.new do
    # all code here
  end
  th.join
end

这很好用,但最后没有响应。

耶耶耶!我找到了解决方案。 我已经将我的服务器从 puma 更改为 unicorn。现在可以正常使用了。