secret_key_base` for ‘production’ environmentが発生したので環境を確認

Railsの環境

[admin@postgresql weather]$ rbenv -v
rbenv 1.1.2-30-gc879cb0
[admin@postgresql weather]$ 

[admin@postgresql weather]$ ruby --version
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]
[admin@postgresql weather]$ rails --version
Rails 6.0.3.2
[admin@postgresql weather]$ 

ProductionへのMigrateionが失敗


[admin@postgresql weather]$ bundle exec rails db:migrate RAILS_ENV=test
== 20200612225551 CreatePrefectures: migrating ================================
-- create_table(:prefectures)
   -> 0.0827s
== 20200612225551 CreatePrefectures: migrated (0.0829s) =======================

== 20200612231434 CreateWeatherForecasts: migrating ===========================
-- create_table(:weather_forecasts)
   -> 0.0807s
== 20200612231434 CreateWeatherForecasts: migrated (0.0810s) ==================

[admin@postgresql weather]$ bundle exec rails db:migrate RAILS_ENV=production
rails aborted!
ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `rails credentials:edit`
/home/admin/app/ruby/weather/config/environment.rb:5:in `<main>'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)
[admin@postgresql weather]$ cat /home/admin/app/ruby/weather/config/environment.rb
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
[admin@postgresql weather]$

マスターキーはgit対象外(≒複合鍵が本番にも必要)

必要に応じてmaster.keyを本番環境にコピーするか、RAILS_MASTER_KEY環境変数に設定。

[admin@postgresql weather]$ cat .gitignore | grep -i key
# Ignore master key for decrypting credentials and more.
/config/master.key
[admin@postgresql weather]$ 

オプション (もし鍵をコピーしても上手くいかない場合)
上記コマンドエラーで、rails credentials:editを実行しろとあるが、こちらを実行する場合は先ずは既存の鍵が環境変数等で利用されてない事を確認した方が無難。
既存のcredentials.ymlは削除して新規で認証鍵ペアを作成。

[admin@postgresql weather]$ rm config/credentials.yml.enc 
[admin@postgresql weather]$ EDITOR="vim" bin/rails credentials:edit

マスターキーの設定をproduction.rbでONに設定


[admin@postgresql environments]$ cat production.rb | grep master
  # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
  # or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
  # config.require_master_key = true
  config.require_master_key = true
[admin@postgresql environments]$ 

Migrationの再実行


[admin@postgresql weather]$ bundle exec rails db:migrate RAILS_ENV=production 
== 20200612225551 CreatePrefectures: migrating ================================
-- create_table(:prefectures)
   -> 0.0641s
== 20200612225551 CreatePrefectures: migrated (0.0643s) =======================

== 20200612231434 CreateWeatherForecasts: migrating ===========================
-- create_table(:weather_forecasts)
   -> 0.1899s
== 20200612231434 CreateWeatherForecasts: migrated (0.1904s) ==================

[admin@postgresql weather]$ 

スキーマにオブジェクトが作成されいる事を確認

スキーマが出来たのでデータを投入して完了


[admin@postgresql weather]$ bundle exec rails db:seed_fu RAILS_ENV=production

== Seed from /home/admin/app/ruby/weather/db/fixtures/prefecture.rb
 - Prefecture {:id=>1, :name=>"北海道", :ename=>"hokkaido"}
 - Prefecture {:id=>2, :name=>"青森県", :ename=>"aomori"}
 - Prefecture {:id=>3, :name=>"岩手県", :ename=>"iwate"}
 - Prefecture {:id=>4, :name=>"宮城県", :ename=>"miyagi"}
 - Prefecture {:id=>5, :name=>"秋田県", :ename=>"akita"}
 - Prefecture {:id=>6, :name=>"山形県", :ename=>"yamagata"}
 - Prefecture {:id=>7, :name=>"福島県", :ename=>"fukushima"}
 - Prefecture {:id=>8, :name=>"茨城県", :ename=>"ibaraki"}
 - Prefecture {:id=>9, :name=>"栃木県", :ename=>"tochigi"}
 - Prefecture {:id=>10, :name=>"群馬県", :ename=>"gunma"}
 - Prefecture {:id=>11, :name=>"埼玉県", :ename=>"saitama"}
 - Prefecture {:id=>12, :name=>"千葉県", :ename=>"chiba"}
 - Prefecture {:id=>13, :name=>"東京都", :ename=>"tokyo"}
 - Prefecture {:id=>14, :name=>"神奈川県", :ename=>"kanagawa"}
 - Prefecture {:id=>15, :name=>"新潟県", :ename=>"niigata"}
 - Prefecture {:id=>16, :name=>"富山県", :ename=>"toyama"}
 - Prefecture {:id=>17, :name=>"石川県", :ename=>"ishikawa"}
 - Prefecture {:id=>18, :name=>"福井県", :ename=>"fukui"}
 - Prefecture {:id=>19, :name=>"山梨県", :ename=>"yamanashi"}
 - Prefecture {:id=>20, :name=>"長野県", :ename=>"nagano"}
 - Prefecture {:id=>21, :name=>"岐阜県", :ename=>"gifu"}
 - Prefecture {:id=>22, :name=>"静岡県", :ename=>"shizuoka"}
 - Prefecture {:id=>23, :name=>"愛知県", :ename=>"aichi"}
 - Prefecture {:id=>24, :name=>"三重県", :ename=>"mie"}
 - Prefecture {:id=>25, :name=>"滋賀県", :ename=>"shiga"}
 - Prefecture {:id=>26, :name=>"京都府", :ename=>"kyoto"}
 - Prefecture {:id=>27, :name=>"大阪府", :ename=>"osaka"}
 - Prefecture {:id=>28, :name=>"兵庫県", :ename=>"hyogo"}
 - Prefecture {:id=>29, :name=>"奈良県", :ename=>"nara"}
 - Prefecture {:id=>30, :name=>"和歌山県", :ename=>"wakayama"}
 - Prefecture {:id=>31, :name=>"鳥取県", :ename=>"tottori"}
 - Prefecture {:id=>32, :name=>"島根県", :ename=>"shimane"}
 - Prefecture {:id=>33, :name=>"岡山県", :ename=>"okayama"}
 - Prefecture {:id=>34, :name=>"広島県", :ename=>"hiroshima"}
 - Prefecture {:id=>35, :name=>"山口県", :ename=>"yamaguchi"}
 - Prefecture {:id=>36, :name=>"徳島県", :ename=>"tokushima"}
 - Prefecture {:id=>37, :name=>"香川県", :ename=>"kagawa"}
 - Prefecture {:id=>38, :name=>"愛媛県", :ename=>"ehime"}
 - Prefecture {:id=>39, :name=>"高知県", :ename=>"kochi"}
 - Prefecture {:id=>40, :name=>"福岡県", :ename=>"fukuoka"}
 - Prefecture {:id=>41, :name=>"佐賀県", :ename=>"saga"}
 - Prefecture {:id=>42, :name=>"長崎県", :ename=>"nagasaki"}
 - Prefecture {:id=>43, :name=>"熊本県", :ename=>"kumamoto"}
 - Prefecture {:id=>44, :name=>"大分県", :ename=>"oita"}
 - Prefecture {:id=>45, :name=>"宮崎県", :ename=>"miyazaki"}
 - Prefecture {:id=>46, :name=>"鹿児島県", :ename=>"kagoshima"}
 - Prefecture {:id=>47, :name=>"沖縄県", :ename=>"okinawa"}
[admin@postgresql weather]$ 


RailsのGem seed-fuを利用して都道府県の初期データを作成する

都道府県番号(厚生労働省)

#### Prefecture Tableの準備

[admin@postgresql weather]$ bundle exec rails g model prefecture
      invoke  active_record
      create    db/migrate/20200612225551_create_prefectures.rb
      create    app/models/prefecture.rb
      invoke    test_unit
      create      test/models/prefecture_test.rb
      create      test/fixtures/prefectures.yml
[admin@postgresql weather]$ 

[admin@postgresql weather]$ vim db/migrate/20200612225551_create_prefectures.rb
[admin@postgresql weather]$ cat db/migrate/20200612225551_create_prefectures.rb
class CreatePrefectures < ActiveRecord::Migration[6.0]
  def change
    create_table :prefectures do |t|
      t.string :name, null: false,  comment: "都道府県"
      t.timestamps
    end
  end
end
[admin@postgresql weather]$ 


[admin@postgresql weather]$ bundle exec rails db:migrate
== 20200612225551 CreatePrefectures: migrating ================================
-- create_table(:prefectures)
   -> 0.1382s
== 20200612225551 CreatePrefectures: migrated (0.1387s) =======================


#### Prefecture Tableの確認


weather_development-# \d prefectures;
                                           テーブル"public.prefectures"
     列     |               型               | 照合順序 | Null 値を許容 |               デフォルト                
------------+--------------------------------+----------+---------------+-----------------------------------------
 id         | bigint                         |          | not null      | nextval('prefectures_id_seq'::regclass)
 name       | character varying              |          | not null      | 
 created_at | timestamp(6) without time zone |          | not null      | 
 updated_at | timestamp(6) without time zone |          | not null      | 
インデックス:
    "prefectures_pkey" PRIMARY KEY, btree (id)
参照元:
    TABLE "weather_forecasts" CONSTRAINT "fk_rails_514be57da6" FOREIGN KEY (prefecture_id) REFERENCES prefectures(id)


#### Gem(seed-fu)のインストールとデータの準備

[admin@postgresql weather]$ tail Gemfile
# https://github.com/mbleigh/seed-fu
  gem 'seed-fu'

[admin@postgresql weather]$ bundle install
Fetching seed-fu 2.3.9
Installing seed-fu 2.3.9
<SNIP>

[admin@postgresql weather]$ cat db/fixtures/prefecture.rb 
Prefecture.seed(:id,
  { :id => 1, :name => "北海道" },
  { :id => 2, :name => "青森県" },
  { :id => 3, :name => "岩手県" },
  { :id => 4, :name => "宮城県" },
  { :id => 5, :name => "秋田県" },
  { :id => 6, :name => "山形県" },
  { :id => 7, :name => "福島県" },
  { :id => 8, :name => "茨城県" },
  { :id => 9, :name => "栃木県" },
  { :id => 10, :name => "群馬県" },
  { :id => 11, :name => "埼玉県" },
  { :id => 12, :name => "千葉県" },
  { :id => 13, :name => "東京都" },
  { :id => 14, :name => "神奈川県" },
  { :id => 15, :name => "新潟県" },
  { :id => 16, :name => "富山県" },
  { :id => 17, :name => "石川県" },
  { :id => 18, :name => "福井県" },
  { :id => 19, :name => "山梨県" },
  { :id => 20, :name => "長野県" },
  { :id => 21, :name => "岐阜県" },
  { :id => 22, :name => "静岡県" },
  { :id => 23, :name => "愛知県" },
  { :id => 24, :name => "三重県" },
  { :id => 25, :name => "滋賀県" },
  { :id => 26, :name => "京都府" },
  { :id => 27, :name => "大阪府" },
  { :id => 28, :name => "兵庫県" },
  { :id => 29, :name => "奈良県" },
  { :id => 30, :name => "和歌山県" },
  { :id => 31, :name => "鳥取県" },
  { :id => 32, :name => "島根県" },
  { :id => 33, :name => "岡山県" },
  { :id => 34, :name => "広島県" },
  { :id => 35, :name => "山口県" },
  { :id => 36, :name => "徳島県" },
  { :id => 37, :name => "香川県" },
  { :id => 38, :name => "愛媛県" },
  { :id => 39, :name => "高知県" },
  { :id => 40, :name => "福岡県" },
  { :id => 41, :name => "佐賀県" },
  { :id => 42, :name => "長崎県" },
  { :id => 43, :name => "熊本県" },
  { :id => 44, :name => "大分県" },
  { :id => 45, :name => "宮崎県" },
  { :id => 46, :name => "鹿児島県" },
  { :id => 47, :name => "沖縄県" }
)
[admin@postgresql weather]$ 

#### Gem(seed-fu)にてデータの投入


[admin@postgresql weather]$ bundle exec rails db:seed_fu

== Seed from /home/admin/app/ruby/weather/db/fixtures/prefecture.rb
 - Prefecture {:id=>1, :name=>"北海道"}
 - Prefecture {:id=>2, :name=>"青森県"}
 - Prefecture {:id=>3, :name=>"岩手県"}
 - Prefecture {:id=>4, :name=>"宮城県"}
 - Prefecture {:id=>5, :name=>"秋田県"}
 - Prefecture {:id=>6, :name=>"山形県"}
 - Prefecture {:id=>7, :name=>"福島県"}
 - Prefecture {:id=>8, :name=>"茨城県"}
 - Prefecture {:id=>9, :name=>"栃木県"}
 - Prefecture {:id=>10, :name=>"群馬県"}
 - Prefecture {:id=>11, :name=>"埼玉県"}
 - Prefecture {:id=>12, :name=>"千葉県"}
 - Prefecture {:id=>13, :name=>"東京都"}
 - Prefecture {:id=>14, :name=>"神奈川県"}
 - Prefecture {:id=>15, :name=>"新潟県"}
 - Prefecture {:id=>16, :name=>"富山県"}
 - Prefecture {:id=>17, :name=>"石川県"}
 - Prefecture {:id=>18, :name=>"福井県"}
 - Prefecture {:id=>19, :name=>"山梨県"}
 - Prefecture {:id=>20, :name=>"長野県"}
 - Prefecture {:id=>21, :name=>"岐阜県"}
 - Prefecture {:id=>22, :name=>"静岡県"}
 - Prefecture {:id=>23, :name=>"愛知県"}
 - Prefecture {:id=>24, :name=>"三重県"}
 - Prefecture {:id=>25, :name=>"滋賀県"}
 - Prefecture {:id=>26, :name=>"京都府"}
 - Prefecture {:id=>27, :name=>"大阪府"}
 - Prefecture {:id=>28, :name=>"兵庫県"}
 - Prefecture {:id=>29, :name=>"奈良県"}
 - Prefecture {:id=>30, :name=>"和歌山県"}
 - Prefecture {:id=>31, :name=>"鳥取県"}
 - Prefecture {:id=>32, :name=>"島根県"}
 - Prefecture {:id=>33, :name=>"岡山県"}
 - Prefecture {:id=>34, :name=>"広島県"}
 - Prefecture {:id=>35, :name=>"山口県"}
 - Prefecture {:id=>36, :name=>"徳島県"}
 - Prefecture {:id=>37, :name=>"香川県"}
 - Prefecture {:id=>38, :name=>"愛媛県"}
 - Prefecture {:id=>39, :name=>"高知県"}
 - Prefecture {:id=>40, :name=>"福岡県"}
 - Prefecture {:id=>41, :name=>"佐賀県"}
 - Prefecture {:id=>42, :name=>"長崎県"}
 - Prefecture {:id=>43, :name=>"熊本県"}
 - Prefecture {:id=>44, :name=>"大分県"}
 - Prefecture {:id=>45, :name=>"宮崎県"}
 - Prefecture {:id=>46, :name=>"鹿児島県"}
 - Prefecture {:id=>47, :name=>"沖縄県"}
[admin@postgresql weather]$ 

#### データの確認
都道府県データが正常に作成されている事を確認しました。

weather_development=# select * from prefectures;
 id |   name   |         created_at         |         updated_at         
----+----------+----------------------------+----------------------------
  1 | 北海道   | 2020-06-12 23:54:33.283651 | 2020-06-12 23:54:33.283651
  2 | 青森県   | 2020-06-12 23:54:33.294884 | 2020-06-12 23:54:33.294884
  3 | 岩手県   | 2020-06-12 23:54:33.301876 | 2020-06-12 23:54:33.301876
  4 | 宮城県   | 2020-06-12 23:54:33.309521 | 2020-06-12 23:54:33.309521
  5 | 秋田県   | 2020-06-12 23:54:33.315667 | 2020-06-12 23:54:33.315667
  6 | 山形県   | 2020-06-12 23:54:33.322739 | 2020-06-12 23:54:33.322739
  7 | 福島県   | 2020-06-12 23:54:33.330228 | 2020-06-12 23:54:33.330228
  8 | 茨城県   | 2020-06-12 23:54:33.352692 | 2020-06-12 23:54:33.352692
  9 | 栃木県   | 2020-06-12 23:54:33.361259 | 2020-06-12 23:54:33.361259
 10 | 群馬県   | 2020-06-12 23:54:33.368557 | 2020-06-12 23:54:33.368557
 11 | 埼玉県   | 2020-06-12 23:54:33.377314 | 2020-06-12 23:54:33.377314
 12 | 千葉県   | 2020-06-12 23:54:33.385298 | 2020-06-12 23:54:33.385298
 13 | 東京都   | 2020-06-12 23:54:33.394371 | 2020-06-12 23:54:33.394371
 14 | 神奈川県 | 2020-06-12 23:54:33.40101  | 2020-06-12 23:54:33.40101
 15 | 新潟県   | 2020-06-12 23:54:33.409158 | 2020-06-12 23:54:33.409158
 16 | 富山県   | 2020-06-12 23:54:33.416567 | 2020-06-12 23:54:33.416567
 17 | 石川県   | 2020-06-12 23:54:33.423705 | 2020-06-12 23:54:33.423705
 18 | 福井県   | 2020-06-12 23:54:33.434071 | 2020-06-12 23:54:33.434071
 19 | 山梨県   | 2020-06-12 23:54:33.464188 | 2020-06-12 23:54:33.464188
 20 | 長野県   | 2020-06-12 23:54:33.473083 | 2020-06-12 23:54:33.473083
 21 | 岐阜県   | 2020-06-12 23:54:33.483633 | 2020-06-12 23:54:33.483633
 22 | 静岡県   | 2020-06-12 23:54:33.4898   | 2020-06-12 23:54:33.4898
 23 | 愛知県   | 2020-06-12 23:54:33.507801 | 2020-06-12 23:54:33.507801
 24 | 三重県   | 2020-06-12 23:54:33.516001 | 2020-06-12 23:54:33.516001
 25 | 滋賀県   | 2020-06-12 23:54:33.523702 | 2020-06-12 23:54:33.523702
 26 | 京都府   | 2020-06-12 23:54:33.533514 | 2020-06-12 23:54:33.533514
 27 | 大阪府   | 2020-06-12 23:54:33.541808 | 2020-06-12 23:54:33.541808
 28 | 兵庫県   | 2020-06-12 23:54:33.550734 | 2020-06-12 23:54:33.550734
 29 | 奈良県   | 2020-06-12 23:54:33.557281 | 2020-06-12 23:54:33.557281
 30 | 和歌山県 | 2020-06-12 23:54:33.566571 | 2020-06-12 23:54:33.566571
 31 | 鳥取県   | 2020-06-12 23:54:33.573718 | 2020-06-12 23:54:33.573718
 32 | 島根県   | 2020-06-12 23:54:33.582212 | 2020-06-12 23:54:33.582212
 33 | 岡山県   | 2020-06-12 23:54:33.589471 | 2020-06-12 23:54:33.589471
 34 | 広島県   | 2020-06-12 23:54:33.598941 | 2020-06-12 23:54:33.598941
 35 | 山口県   | 2020-06-12 23:54:33.605716 | 2020-06-12 23:54:33.605716
 36 | 徳島県   | 2020-06-12 23:54:33.614624 | 2020-06-12 23:54:33.614624
 37 | 香川県   | 2020-06-12 23:54:33.621642 | 2020-06-12 23:54:33.621642
 38 | 愛媛県   | 2020-06-12 23:54:33.628824 | 2020-06-12 23:54:33.628824
 39 | 高知県   | 2020-06-12 23:54:33.637536 | 2020-06-12 23:54:33.637536
 40 | 福岡県   | 2020-06-12 23:54:33.644695 | 2020-06-12 23:54:33.644695
 41 | 佐賀県   | 2020-06-12 23:54:33.653393 | 2020-06-12 23:54:33.653393
 42 | 長崎県   | 2020-06-12 23:54:33.659903 | 2020-06-12 23:54:33.659903
 43 | 熊本県   | 2020-06-12 23:54:33.66802  | 2020-06-12 23:54:33.66802
 44 | 大分県   | 2020-06-12 23:54:33.675145 | 2020-06-12 23:54:33.675145
 45 | 宮崎県   | 2020-06-12 23:54:33.683799 | 2020-06-12 23:54:33.683799
 46 | 鹿児島県 | 2020-06-12 23:54:33.700625 | 2020-06-12 23:54:33.700625
 47 | 沖縄県   | 2020-06-12 23:54:33.708507 | 2020-06-12 23:54:33.708507
(47 行)

weather_development=# 


RailsのActive Jobによる非同期ジョブスケジューリング
非同期処理を行う為に、ここではSidekiqを利用しています。

Sidekiq: https://github.com/mperham/sidekiq/wiki/Active-Job

SidekiqではKey/Value処理を行う為に、Redisを利用しているので準備

shinya@DESKTOP-A5QLPD0:~/$ sudo apt install redis-server
[sudo] password for shinya:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libjemalloc1 redis-tools
Suggested packages:
  ruby-redis
The following NEW packages will be installed:
  libjemalloc1 redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 43 not upgraded.
Need to get 634 kB of archives.
After this operation, 3012 kB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libjemalloc1 amd64 3.6.0-11 [82.4 kB]
Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 redis-tools amd64 5:4.0.9-1ubuntu0.2 [516 kB]
Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 redis-server amd64 5:4.0.9-1ubuntu0.2 [35.4 kB]
Fetched 634 kB in 4s (159 kB/s)
Selecting previously unselected package libjemalloc1.
(Reading database ... 54906 files and directories currently installed.)
Preparing to unpack .../libjemalloc1_3.6.0-11_amd64.deb ...
Unpacking libjemalloc1 (3.6.0-11) ...
Selecting previously unselected package redis-tools.
Preparing to unpack .../redis-tools_5%3a4.0.9-1ubuntu0.2_amd64.deb ...
Unpacking redis-tools (5:4.0.9-1ubuntu0.2) ...
Selecting previously unselected package redis-server.
Preparing to unpack .../redis-server_5%3a4.0.9-1ubuntu0.2_amd64.deb ...
Unpacking redis-server (5:4.0.9-1ubuntu0.2) ...
Setting up libjemalloc1 (3.6.0-11) ...
Setting up redis-tools (5:4.0.9-1ubuntu0.2) ...
Setting up redis-server (5:4.0.9-1ubuntu0.2) ...
invoke-rc.d: could not determine current runlevel
Created symlink /etc/systemd/system/redis.service → /lib/systemd/system/redis-server.service.
Created symlink /etc/systemd/system/multi-user.target.wants/redis-server.service → /lib/systemd/system/redis-server.service.
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Processing triggers for systemd (237-3ubuntu10.28) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Processing triggers for ureadahead (0.100.0-21) ...
shinya@DESKTOP-A5QLPD0:~/$      

Redisを起動

shinya@DESKTOP-A5QLPD0:~/$ redis-server
12214:C 09 Nov 07:40:33.658 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
12214:C 09 Nov 07:40:33.661 # Redis version=4.0.9, bits=64, commit=00000000, modified=0, pid=12214, just started
12214:C 09 Nov 07:40:33.662 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
12214:M 09 Nov 07:40:33.665 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 4.0.9 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 12214
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

12214:M 09 Nov 07:40:37.126 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
12214:M 09 Nov 07:40:37.135 # Server initialized
12214:M 09 Nov 07:40:37.143 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
12214:M 09 Nov 07:40:37.145 * Ready to accept connections

Sidekiqのインストール

shinya@DESKTOP-A5QLPD0:~/$ vim Gemfile
shinya@DESKTOP-A5QLPD0:~/$ cat Gemfile | grep -A2 "Active Job"
### Active Job (A-Sync)
gem 'sidekiq'
shinya@DESKTOP-A5QLPD0:~/$
shinya@DESKTOP-A5QLPD0:~/$ bundle
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies....
Using rake 13.0.0
Using concurrent-ruby 1.1.5
<SNIP>
Fetching sidekiq 6.0.3
Installing sidekiq 6.0.3
Bundle complete! 30 Gemfile dependencies, 109 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
shinya@DESKTOP-A5QLPD0:~/$

Sidekiqの起動

shinya@DESKTOP-A5QLPD0:~/$ bundle exec sidekiq


               m,
               `$b
          .ss,  $$:         .,d$
          `$$P,d$P'    .,md$P"'
           ,$$$$$b/md$$$P^'
         .d$$$$$$/$$$P'
         $$^' `"/$$$'       ____  _     _      _    _
         $:     ,$$:       / ___|(_) __| | ___| | _(_) __ _
         `b     :$$        \___ \| |/ _` |/ _ \ |/ / |/ _` |
                $$:         ___) | | (_| |  __/   <| | (_| |
                $$         |____/|_|\__,_|\___|_|\_\_|\__, |
              .d$$                                       |_|


2019-11-08T22:48:19.284Z pid=12548 tid=oxyucamm4 INFO: Running in ruby 2.5.1p57 (2018-03-29 revision 63029) &#91;x86_64-linux&#93;
2019-11-08T22:48:19.286Z pid=12548 tid=oxyucamm4 INFO: See LICENSE and the LGPL-3.0 for licensing details.
2019-11-08T22:48:19.288Z pid=12548 tid=oxyucamm4 INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org
2019-11-08T22:48:19.290Z pid=12548 tid=oxyucamm4 INFO: Booting Sidekiq 6.0.3 with redis options {:id=>"Sidekiq-server-PID-12548", :url=>nil}
2019-11-08T22:48:19.296Z pid=12548 tid=oxyucamm4 INFO: Starting processing, hit Ctrl-C to stop

Sidekiq

SidekiqをRailsで利用する為の設定を入れる

shinya@DESKTOP-A5QLPD0:~/$ ls config/environments/
development.rb  production.rb  test.rb
shinya@DESKTOP-A5QLPD0:~/$ vim config/environments/development.rb
shinya@DESKTOP-A5QLPD0:~/$ cat config/environments/development.rb | grep -A2 "Active Job"
  # Active Job
  config.active_job.queue_adapter = :sidekiq
shinya@DESKTOP-A5QLPD0:~/$

テストジョブの作成

1) Generatorでジョブのテンプレートを作成

shinya@DESKTOP-A5QLPD0:~/$ bin/rails generate job sample
Running via Spring preloader in process 13642
      invoke  test_unit
      create    test/jobs/sample_job_test.rb
      create  app/jobs/sample_job.rb
shinya@DESKTOP-A5QLPD0:~/$ cat test/jobs/sample_job_test.rb
require 'test_helper'

class SampleJobTest < ActiveJob::TestCase
  # test "the truth" do
  #   assert true
  # end
end
shinya@DESKTOP-A5QLPD0:~/$ cat app/jobs/sample_job.rb
class SampleJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Do something later
  end
end
shinya@DESKTOP-A5QLPD0:~/$

&#91;/SHELL&#93;

2) テストジョブを作成

&#91;SHELL&#93;

shinya@DESKTOP-A5QLPD0:~/$ vim app/jobs/sample_job.rb
shinya@DESKTOP-A5QLPD0:~/$ cat app/jobs/sample_job.rb
class SampleJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Do something later
    Sidekiq::Logging.logger.info "Sidekiqのテストジョブ実行"
  end
end
shinya@DESKTOP-A5QLPD0:~/$

&#91;/SHELL&#93;

3) ジョブをCALLする

&#91;SHELL&#93;
shinya@DESKTOP-A5QLPD0:~/$ cat app/controllers/document_controller.rb | grep Sample
        SampleJob.perform_later
        #SampleJob.set(wait: 3.seconds).perform_later
        #SampleJob.set(wait: 1.week).perform_later
shinya@DESKTOP-A5QLPD0:~/$
&#91;/SHELL&#93;


<strong>特定処理を実行後の非同期処理とログの確認</strong>

[SHELL]

---==_mimepart_5dc5fe832cc3c_36023ffff4bcf99c6866e--

document: {"id"=>180, "name"=>"SidekiqテストASYNCジョブ", "description"=>"SidekiqテストASYNCジョブ", "created_at"=>Sat, 09 Nov 2019 08:47:14 JST +09:00, "updated_at"=>Sat, 09 Nov 2019 08:47:14 JST +09:00, "user_id"=>16}
[ActiveJob] Enqueued SampleJob (Job ID: 444d268d-3fee-4fcf-b0d1-3eef7fb9bf8c) to Sidekiq(default)
Redirected to http://localhost:3000/document/180
Completed 302 Found in 790ms (ActiveRecord: 3.2ms)

メモ:購入完了や登録メール等の処理を非同期にする事でショッピングカートや登録ページで待ちが発生する事をふせぐのに使えそう。