Best way to combine fragment and object caching for memcached and Rails

前端 未结 5 640
故里飘歌
故里飘歌 2021-01-31 12:11

Lets say you have a fragment of the page which displays the most recent posts, and you expire it in 30 minutes. I\'m using Rails here.

<% cache(\"recent_posts         


        
5条回答
  •  长发绾君心
    2021-01-31 12:52

    Evan Weaver's Interlock Plugin solves this problem.

    You can also implement something like this yourself easily if you need different behavior, such as more fine grained control. The basic idea is to wrap your controller code in a block that is only actually executed if the view needs that data:

    # in FooController#show
    @foo_finder = lambda{ Foo.find_slow_stuff }
    
    # in foo/show.html.erb
    cache 'foo_slow_stuff' do
      @foo_finder.call.each do 
        ...
      end
    end
    

    If you're familiar with the basics of ruby meta programming it's easy enough to wrap this up in a cleaner API of your taste.

    This is superior to putting the finder code directly in the view:

    • keeps the finder code where developers expect it by convention
    • keeps the view ignorant of the model name/method, allowing more view reuse

    I think cache_fu might have similar functionality in one of it's versions/forks, but can't recall specifically.

    The advantage you get from memcached is directly related to your cache hit rate. Take care not to waste your cache capacity and cause unnecessary misses by caching the same content multiple times. For example, don't cache a set of record objects as well as their html fragment at the same time. Generally fragment caching will offer the best performance, but it really depends on the specifics of your application.

提交回复
热议问题