[RAILS] The story of managing session information by introducing gem Redis

What did you do

We are implementing a certain Rails curriculum. I was supposed to use Redis to manage session information, but since this is my first gem, I tried to check the contents easily.

The execution environment is as follows.

Official notice as of December 2020

First of all, when I tried to grasp the contents in Official Document, the following was written at the beginning.

Rails 5.2.0 includes a ready-to-use Redis cache store, so if you just need to store your fragment cache in Redis, you don't need this gem anymore. Maintenance of the redis-activesupport gem will continue due to security and compatibility issues, but we are not accepting new features. We continue to actively maintain all other gems in the redis-store family, including redis-action packs for session management and redis-rack-cache for HTTP cache storage.

Th-This is,,,,. Does that mean you don't need this gem above Rails 5.2.0? ?? For the time being, I didn't understand what the word fragment cache was in the above sentence, so I looked it up.

According to it, the fragment cache is a cache for reloading view information, isn't it?

In other words, the above description says that this gem is unnecessary if you only cache the view information, so it seems that you can continue to use it for this session information management. Was good.

However, the Session information management part of the official document also says, "Please use redis-action pack directly in the future", so I will use this in the future. May be good ^^

Overview of Gem

With the official information, it was difficult to grasp "what kind of gem it is", so I referred to this article.

What is Redis? Introducing Redis to Rails

According to it, Redis seems to have the following features.

Famous as a cache system, one of NoSQL -KVS (key-value store) among NoSQL. Save the key / value combination. ・ Can be used for various data types ・ String, List, Set, Sorted Set, Hash ・ High speed because it is in-memory ・ Persistence can be set ・ Single thread ・ Scale out is possible ・ Usage ・ When handling data with an expiration date such as a session -When dealing with processing that requires running heavy SQL such as ranking data

... I didn't understand many words, so I'll add what I searched for below.

--NoSQL ... A database language that allows you to manipulate data without using SQL. This is json and so on. --In-memory ... It depends mainly on the memory for data storage, not the database that stores data on disk or SSD. --Single thread ... Processing that can be written with one line when a line is drawn from the start to the end of processing, non-branching processing.

...So that's it. I finally got an overview.

Installation procedure

Let's introduce it. First, put the following in Gemfile and bundle install.

Gemfile


gem 'redis-rails'

Next, in config/initializers/session_store.rb (or create a new one), enter the following. In addition, if this part is left as Official description, an error occurred in relation to CSRF, so I wrote as follows with reference to This blog article. ..

config/initializers/session_store.rb


MyApp::Application.config.session_store :redis_store, expire_after: 1.day, servers: {
  host: "localhost",
  port: 6379,
  namespace: "user_sessions",
  signed: true,
  secure: true
}

The explanation of each option was also officially written, so I will write it down with the help of Google Translate below.

--servers ... Array of URLs for Redis servers trying to retrieve data (6379 is Redis' default value) --expire_after ... The default TTL for the session key (https://wa3.i-3-i.info/word13138.html). This is also set as the expiration date for cookies generated by the session store. --key ... The name of the cookie on the client side --threadsafe ... For applications that run on multiple instances. Set this to false if you want to disable the global mutex lock for session data (Mechanism that prevents more than one person from using). This is true by default, which means that mutexes are enabled. --signed ... Uses signed/encrypted cookies to store local sessions on client machines to prevent malicious users from tampering with their content --secure ... Guarantee that HTTP cookies are forwarded from the server to the client over a secure (HTTPS) connection

Well, I got a good understanding of the options. Then, I will use it immediately.

How to use

Redis makes session information visible to developers in the form of ** putting session information into the Redis server **. Therefore, you must first start the Redis server (before launching the Rails application).

$ redis-server

Please note that an error will occur if you start the Rails server without starting the Redis server after installing Redis.

Then run redis-cli in a separate window.

$ redis cli
127.0.0.1:6379> #You can enter a command

After that, you can read and write Redis server information by entering various commands.

Command operation

All Redis command information can be viewed from here, but here we will only introduce enough content to view session information.

In addition, this blog article was also very helpful.

You can see all the keys registered with ** KEYS * **.

> KEYS *
1) "user_sessions:2::f7ab4de876c20536e1e391a21bac...."

Earlier, I specified namespace:" user_sessions " in the Redis settings, so the session information is prefixed with user_sessions. Wildcards can be used for KEYS, so

If you enter ** KEYS user_sessions * **,

> keys user_sessions*
1) "user_sessions:2::f7ab4de876c20536e1e391a21bac...."

You can only see the keys for the user session. (The display is the same as before ^^;)

In Redis, it seems that the method of getting the Value value differs depending on the data type. So, first check the data type of KEY you got earlier.

You can check the data type with ** TYPE key name **.

> type 1) "user_sessions:2::f7ab4de876c20536e1e391a21bac...."
string

Since it is GET to get the value of the string type key,

If you enter ** GET key name **, you can see the value value of session.

get 1) "user_sessions:2::f7ab4de876c20536e1e391a21bac...."
"\x04\b{\aI\"\x10_csrf_token\x06:\x06EFI\...."

Session information looks like this, doesn't it? .. ..

Impressions

That's all for implementation. I investigated it very carefully because it was the first gem to use and the problem was to output it, but thanks to that, I learned a lot about how to read the official document. Also, if you read the document carefully and then start implementing it, you will be able to understand how the gem works, so error resolution will be quicker.

I will continue to do my best.

Postscript: About the matter that a file called dump.rdb is generated

In my case, the file dump.rdb was generated in the current directory by installing Redis, but I was able to avoid it by the following method.

dump.rdb is generated in the current directory

Recommended Posts

The story of managing session information by introducing gem Redis
The story of introducing Ajax communication to ruby
The story of not knowing the behavior of String by passing Java by reference
[Java version] The story of serialization
The story of @ViewScoped consuming memory
The story of encountering Spring custom annotation
[Rails] Temporary retention of data by session
Introducing the features of JavaFX SceneBuilder container
The story of updating SonarQube's Docker Container
The process of understanding Gemfile by non-engineers
[Swift] Termination of the program by assertion
The story of RxJava suffering from NoSuchElementException
The story of AppClip support in Anyca
The story received by Java SE11 silver
The story of writing Java in Emacs
The process of introducing Vuetify to Rails
The contents of the data saved by CarrierWave.