LoginSignup
5
3

More than 5 years have passed since last update.

Ecto Model をMemcachedとかにキャッシュしてみる

Last updated at Posted at 2016-08-26

Ecto Model をキャッシュする

ここでは memcache_client を使います。

例えばこんなUserモデルがあります

defmodule Models.User do
  use Web, :model

  schema "users" do
    field :username, :string
    field :email, :string

    timestamps
  end

  @required_fields ~w(username email)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.
  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

Userをそのまま入れてみます

iex(1)> user = %Models.User{}
%Models.User{__meta__: #Ecto.Schema.Metadata<:built>, username: nil, email: nil, inserted_at: nil, updated_at: nil}

iex(2)> Memcache.Client.set("key", user)
** (ArgumentError) argument error
    (memcache_client) lib/memcache_client.ex:253: Memcache.Client.store_request/4
    (memcache_client) lib/memcache_client.ex:242: Memcache.Client.do_store/4

普通に入れてもそのままではエラーが起きます。

バイナリに変換してセットする

iex(3)> data = :erlang.term_to_binary(user)
<<131, 116, 0, 0, 0, 17, 100, 0, 8, 95, 95, 109, 101, 116, 97, 95, 95, 116, 0,
  0, 0, 4, 100, 0, 10, 95, 95, 115, 116, 114, 117, 99, 116, 95, 95, 100, 0, 27,
  69, 108, 105, 120, 105, 114, 46, 69, 99, 116, 111, 46, ...>>

iex(4)> Memcache.Client.set("key", data)
%Memcache.Client.Response{cas: 1, data_type: nil, extras: "", key: "",
 status: :ok, value: ""}

ゲット時はバイナリから Ecto Model に変換します

iex(5)> response = Memcache.Client.get("key")
%Memcache.Client.Response{cas: 1, data_type: 0, extras: <<0, 0, 0, 0>>, key: "",
 status: :ok,
 value: <<131, 116, 0, 0, 0, 17, 100, 0, 8, 95, 95, 109, 101, 116, 97, 95, 95,
   116, 0, 0, 0, 4, 100, 0, 10, 95, 95, 115, 116, 114, 117, 99, 116, 95, 95,
   100, 0, 27, 69, 108, 105, 120, 105, 114, 46, ...>>}

iex(6)> user = :erlang.binary_to_term(response.value)
%Models.User{__meta__: #Ecto.Schema.Metadata<:built>, username: nil, email: nil, inserted_at: nil, updated_at: nil}

バイナリにしてしまえばMapでもStructでも何でもmemcacheやredisにセット出来るようになります。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3