LoginSignup
11
7

More than 5 years have passed since last update.

今更ながらPhoenixでRedisをsessionに使う

Posted at

今更ですが、PhoenixでRedisをsessionに使う手順をメモっておきます。

必要なライブラリのインストール

plug_session_redisを使います。

mix.exsにライブラリを追加。

mix.exs
def application do
  [mod: {MyApp, []}
  applications: [
    # 省略
    :plug_session_redis, # これを追加
    ],
  ]
end

defp deps do
  [{:phoenix, "~> 1.1.4"},
   # 省略
   {:plug_session_redis, "~> 0.1"}, # これを追加
  ]
end

で、mix deps.getします

$ mix deps.get

設定周り

config.exsかdev.exsかprod.exsか、必要に応じて設定分けます。
今回は一旦config.exs

config.exs
# 末尾に追加(末尾じゃなきゃいけないわけじゃないけど)
config :plug_session_redis, :config,
  name: :redis_sessions,
  pool: [size: 2, max_overflow: 5],
  redis: [host: '127.0.0.1', port: 6379]

そしてendpoint.exにplugを追加

lib/my_app/endpoint.ex
# デフォルトのcookieをコメントアウト
# plug Plug.Session,
#   store: :cookie,
#   key: "_my_app_key",
#   signing_salt: "8hQFzwFb"

# 以下を追加
plug Plug.Session,
  store: PlugSessionRedis.Store,
  key: "_my_app_key",
  table: :redis_sessions,
  signing_salt: "8hQFzwFb",
  encryption_salt: "jefa7xG",
  ttl: 360

必要な設定は以上です!

試す

取り敢えず適当にpage_controller辺りで表示させてみます。

page_controller.ex
defmodule MyApp.PageController do
  use MyApp.Web, :controller

  def index(conn, _param) do
    session = get_session(conn, :count) || 0

    conn = put_session(conn, :count, session + 1)

    render conn, "index.html", session: get_session(conn, :count)
  end
end

htmlはslimで書いてます

web/templates/page/index.html.slim
/ 邪魔くさいのでjumbotron以外は消して出力
.jumbotron
 = @session

リロードするたびに数字がインクリメントされていることが確認できました!

スクリーンショット 2016-03-30 18.18.40.png

スクリーンショット 2016-03-30 18.18.46.png

11
7
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
11
7