Mongoid Cache Sweeper with Mongoid::Observer

rails3在config/application.rb

rails2在config/environment.rb

# mongoid observers/sweepers
config.mongoid.observers = Dir["#{config.root}/app/observers/*.rb"].collect do |full_name|
  File.basename(full_name,'.rb').to_sym
end

创建文件 app/observers/user_observer.rb

class UserObserver < Mongoid::Observer
  def after_create(record)
    expire_cache_for(record)
  end

  def after_update(record)
    expire_cache_for(record)
  end

  def after_destroy(record)
    expire_cache_for(record)
  end

  private

  def expire_cache_for(record)
    # 删除user过期的片段缓存
    @u ||= ActionController::Base.new
    @u.expire_fragment("user_#{record.id}")

    # 删除user过期关系的片段缓存
    if record.news.present?
      @c.expire_fragment("news_#{record.news.id}")
    end

    # 删除user过期关系的页面缓存
    @c.expire_page("/my/#{record.id}")

    # 删除memcached的缓存
    Rails.cache.delete([:user_info, "#{record.id}", :login])
  end
end

参考

http://mongoid.org/en/mongoid/docs/callbacks.html

Comments