その他
    ホーム 技術発信 DoRuby memcachedを使ってみる

    memcachedを使ってみる

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    どうもメガネです。

    今日は、memcachedをrailsで使用したいと思います。memcachedとは
    http://gihyo.jp/dev/feature/01/memcached/0001

    今回はcache_fuというpluginsを使用します。

    1.memcachedのインストール&起動
    # yum install memcached
    # /etc/init.d/memcached start

    2.memcache-clientのインストール
    # gem install memcache-client

    3.cache_fuのプラグインの設置
    cache_fuのダウンロード後、解凍してvendor/plugins以下に設置
    http://github.com/defunkt/cache_fu

    4.config/memcached.ymlを作成
    内容は以下の通り(適当に変えてください。)

    defaults:
      ttl: 1800
      readonly: false
      urlencode: false
      c_threshold: 10000
      compression: true
      debug: false
      namespace: sns-decop
      session_servers: false
      memory: 64
      benchmarking: true
      raise_errors: false
      fast_hash: false
      fastest_hash: false

    development:
      sessions: true
      fragments: false
      servers: localhost:11211

    以上で準備完了。

    今回は、Userモデルがあることを仮定して、ユーザ一覧をmemcacheに格納したいと思います。

    Userモデルの修正
    class User < ActiveRecord::Base
      #10分データ保持する
      acts_as_cached :ttl => 10.minutes

      def self.find_all
        # get_cache(“find_all”)にデータがなければ、findしてget_cacheに追加する
        users = self.get_cache(“find_all”) do
          users = User.find :all
        end
      end
    end

    class UsersController < ApplicationController

      def index
        @users = User.find_all
      end

    end

    上のような感じでデータが取得できます。
    便利なのでぜひ使用してみてください。