如何在我的Rails应用程序中避免竞态条件?

21

我有一个非常简单的Rails应用程序,允许用户在一组课程中注册他们的出席情况。ActiveRecord模型如下:

class Course < ActiveRecord::Base
  has_many :scheduled_runs
  ...
end

class ScheduledRun < ActiveRecord::Base
  belongs_to :course
  has_many :attendances
  has_many :attendees, :through => :attendances
  ...
end

class Attendance < ActiveRecord::Base
  belongs_to :user
  belongs_to :scheduled_run, :counter_cache => true
  ...
end

class User < ActiveRecord::Base
  has_many :attendances
  has_many :registered_courses, :through => :attendances, :source => :scheduled_run
end

ScheduledRun实例有限数量的名额,一旦达到限制,就无法接受更多的出席。

def full?
  attendances_count == capacity
end

attendances_count 是一个计数器缓存列,用于保存针对特定 ScheduledRun 记录创建的 Attendances 关联数量。

我的问题是我不完全知道正确的方法来确保当1个或多个人同时尝试注册课程的最后一个可用位置时,不会发生竞争条件。

我的 Attendance 控制器如下所示:

class AttendancesController < ApplicationController
  before_filter :load_scheduled_run
  before_filter :load_user, :only => :create

  def new
    @user = User.new
  end

  def create
    unless @user.valid?
      render :action => 'new'
    end

    @attendance = @user.attendances.build(:scheduled_run_id => params[:scheduled_run_id])

    if @attendance.save
      flash[:notice] = "Successfully created attendance."
      redirect_to root_url
    else
      render :action => 'new'
    end

  end

  protected
  def load_scheduled_run
    @run = ScheduledRun.find(params[:scheduled_run_id])
  end

  def load_user
    @user = User.create_new_or_load_existing(params[:user])
  end

end

正如你所看到的,它没有考虑 ScheduledRun 实例已经达到容量的情况。

任何对此的帮助将不胜感激。

更新

我不确定这是否是在这种情况下执行乐观锁定的正确方法,但是这是我所做的:

我向 ScheduledRuns 表中添加了两列 -

t.integer :attendances_count, :default => 0
t.integer :lock_version, :default => 0

我还向ScheduledRun模型添加了一个方法:

  def attend(user)
    attendance = self.attendances.build(:user_id => user.id)
    attendance.save
  rescue ActiveRecord::StaleObjectError
    self.reload!
    retry unless full? 
  end

当保存 Attendance 模型时,ActiveRecord 会立即更新 ScheduledRun 模型上的计数器缓存列。以下是显示此操作发生位置的日志输出 -

ScheduledRun Load (0.2ms)   SELECT * FROM `scheduled_runs` WHERE (`scheduled_runs`.`id` = 113338481) ORDER BY date DESC

Attendance Create (0.2ms)   INSERT INTO `attendances` (`created_at`, `scheduled_run_id`, `updated_at`, `user_id`) VALUES('2010-06-15 10:16:43', 113338481, '2010-06-15 10:16:43', 350162832)

ScheduledRun Update (0.2ms)   UPDATE `scheduled_runs` SET `lock_version` = COALESCE(`lock_version`, 0) + 1, `attendances_count` = COALESCE(`attendances_count`, 0) + 1 WHERE (`id` = 113338481)
如果在保存新的Attendance模型之前,ScheduledRun模型发生了后续更新,则这应该触发StaleObjectError异常。此时,如果尚未达到容量限制,则整个过程将重新尝试。

更新#2

接下来是SheduledRun对象上更新后的attend方法,根据@kenn的回答进行更新:

# creates a new attendee on a course
def attend(user)
  ScheduledRun.transaction do
    begin
      attendance = self.attendances.build(:user_id => user.id)
      self.touch # force parent object to update its lock version
      attendance.save # as child object creation in hm association skips locking mechanism
    rescue ActiveRecord::StaleObjectError
      self.reload!
      retry unless full?
    end
  end 
end

你需要使用乐观锁定。这个视频教程将向你展示如何实现:链接文本 - rtacconi
你是什么意思,Dmitry? - Edward
2个回答

13

乐观锁是个不错的选择,但你可能已经注意到了,由于has_many关联中的子对象创建会跳过锁定机制,因此你的代码永远不会触发ActiveRecord :: StaleObjectError异常。请看下面的SQL:

UPDATE `scheduled_runs` SET `lock_version` = COALESCE(`lock_version`, 0) + 1, `attendances_count` = COALESCE(`attendances_count`, 0) + 1 WHERE (`id` = 113338481)

当您更新对象中的属性时,通常会看到以下SQL:

UPDATE `scheduled_runs` SET `updated_at` = '2010-07-23 10:44:19', `lock_version` = 2 WHERE id = 113338481 AND `lock_version` = 1

以上语句展示了乐观锁的实现方式:注意WHERE子句中的lock_version = 1。当出现竞争条件时,并发进程尝试运行此确切查询,但只有第一个进程成功,因为第一个进程原子性地将lock_version更新为2,随后的进程将无法找到该记录,并引发ActiveRecord::StaleObjectError,因为相同记录不再具有lock_version = 1

因此,在您的情况下,可能的解决方法是在创建/销毁子对象之前触摸父对象,例如:

def attend(user)
  self.touch # Assuming you have updated_at column
  attendance = self.attendances.create(:user_id => user.id)
rescue ActiveRecord::StaleObjectError
  #...do something...
end

它并不是为了严格避免竞态条件,但实际上在大多数情况下应该可以工作。


谢谢Kenn。我没有意识到子对象的创建会跳过锁定机制。我还将整个过程包装在一个事务中,这样如果子对象的创建失败,父对象就不会被不必要地更新。 - Cathal

0

你难道不只是需要测试一下@run.full?吗?

def create
   unless @user.valid? || @run.full?
      render :action => 'new'
   end

   # ...
end

编辑

如果您添加了类似以下的验证:

class Attendance < ActiveRecord::Base
   validate :validates_scheduled_run

   def scheduled_run
      errors.add_to_base("Error message") if self.scheduled_run.full?
   end
end

如果关联的 scheduled_run 已满,则不会保存 @attendance

我还没有测试过这段代码...但我相信它是没问题的。


那样做行不通。问题在于@run所代表的记录可能已经被另一个请求更新,导致@run与数据库中所表示的内容不一致。据我所知,乐观锁定是解决这个问题的方法。但是,如何将其应用于关联呢? - Cathal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接