Skip to content

Instantly share code, notes, and snippets.

@JokerCatz
Created January 17, 2020 03:10
Show Gist options
  • Save JokerCatz/90d35b79aeebd39a9fb810c2022413d3 to your computer and use it in GitHub Desktop.
Save JokerCatz/90d35b79aeebd39a9fb810c2022413d3 to your computer and use it in GitHub Desktop.
Rails6 Redis Session Store (serializer by JSON)
# -*- encoding : utf-8 -*-
Rails.application.config.session_store(
:redis_store,
key: "_#{Rails.application.class.parent_name.downcase}_session",
expire_after: 2.days,
threadsafe: true,
url: "redis://127.0.0.1:6379/8",
)
# Redis session store(serializer by JSON) for Rails 6
# need redis / hiredis gem
module ActionDispatch
module Session
class RedisStore < AbstractSecureStore
def initialize(app, options = {})
redis_options = {
driver: options[:driver] || :hiredis,
threadsafe: options.has_key?(:threadsafe) ? options[:threadsafe] : true,
}
if options.has_key?(:cluster)
redis_options[:cluster] = options[:cluster]
else
redis_options[:url] = options[:url] || "redis://127.0.0.1:6379/8"
end
@redis_client = Redis.new(redis_options)
@expire_in = options[:expire_after] || options[:expires_in] || 2.days
@namespace = options[:namespace] || options[:key]
super
end
# Get a session from the cache.
def find_session(env, sid)
unless sid && (session = get_session_with_fallback(sid))
sid, session = generate_sid, {}
end
[sid, session]
end
# Set a session in the cache.
def write_session(env, sid, session, options)
key = cache_key(sid.private_id)
if session
@redis_client.set(key, JSON.dump(session), ex: @expire_in)
else
@redis_client.del(key)
end
sid
end
# Remove a session from the cache.
def delete_session(env, sid, options)
@redis_client.del(cache_key(sid.private_id))
@redis_client.del(cache_key(sid.public_id))
generate_sid
end
private
# Turn the session id into a cache key.
def cache_key(id)
"_#{@namespace}:session_id:#{id}"
end
def get_session_with_fallback(sid)
raw_data = @redis_client.get(cache_key(sid.private_id)) || @redis_client.get(cache_key(sid.public_id))
return JSON.parse(raw_data)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment