One place for hosting & domains

      Sidekiq

      Добавление Sidekiq и Redis в приложение Ruby on Rails


      Введение

      При разработке приложения Ruby on Rails могут возникнуть такие задачи приложения, которые должны выполняться асинхронно. Обработка данных, массовая рассылка электронной почты, взаимодействие с внешними API и другие подобные задачи могут выполняться асинхронно в виде фоновых задач. Использование фоновых задач поможет повысить производительность вашего приложения за счет разгрузки потенциально ресурсоемких задач в фоновую очередь с освобождением первоначального цикла запрос/ответ.

      Sidekiq — одна из наиболее широко используемых инфраструктур фоновых задач, которые можно реализовать в приложении Rails. Она основана на системе хранения пар ключ-значение в оперативной памяти Redis, отличающейся гибкостью и высокой производительностью. Sidekiq использует Redis как хранилище для управления задачами, чтобы обрабатывать тысячи задач в секунду.

      В этом обучающем руководстве мы добавим Redis и Sidekiq в существующее приложение Rails. Мы создадим набор рабочих классов Sidekiq и методов для обработки:

      • Пакетная выгрузка информации о находящихся под угрозой вымирания акулах в базу данных приложения из файла CSV в репозитории проекта.
      • Удаление этих данных.

      После завершения работы мы получим демонстрационное приложение, использующее рабочих и задания для асинхронной обработки задач. Это обучающее руководство даст хорошую основу для добавления системы рабочих и заданий в ваше собственное приложение.

      Предварительные требования

      Для данного обучающего руководства вам потребуется следующее:

      • Локальный компьютер или сервер разработки под управлением Ubuntu 18.04. На используемом для разработки компьютере должен быть пользователь без привилегий root с административными привилегиями, а также брандмауэр, настроенный с помощью ufw. Указания по настройке можно найти в обучающем руководстве Начальная настройка сервера Ubuntu 18.04.
      • Node.js и npm, установленные на локальном компьютере или сервере разработки. В этом обучающем руководстве используются версии Node.js 10.17.0 и npm 6.11.3. Указания по установке Node.js и npm в Ubuntu 18.04 можно найти в разделе Установка с использованием PPA обучающего руководства Установка Node.js в Ubuntu 18.04.
      • Диспетчер пакетов Yarn, установленный на локальном компьютере или сервере разработки. Вы можете следовать указаниям по установке, приведенным в официальной документации.
      • Ruby, rbenv и Rails, установленные на локальном компьютере или сервере разработки в соответствии с указаниями шагов 1-4 обучающего руководства Установка Ruby on Rails с помощью rbenv в Ubuntu 18.04. В этом обучающем руководстве используются версии Ruby 2.5.1, rbenv 1.1.2 и Rails 5.2.3.
      • СУБД SQLite, установленная в соответствии с указаниями шага 1 обучающего руководства Создание приложения Ruby on Rails. В этом обучающем руководстве используется версия СУБД SQLite 3 3.22.0.
      • Система Redis, установленная в соответствии с указаниями шагов 1-3 обучающего руководства Установка и защита Redis в Ubuntu 18.04. В этом обучающем руководстве используется версия Redis 4.0.9.

      Шаг 1 — Клонирование проекта и установка зависимостей

      Нашим первым шагом будет клонирование репозитория rails-bootstrap из учетной записи DigitalOcean Community на GitHub. Этот репозиторий содержит код установки, описанный в обучающем руководстве Добавление Bootstrap в приложение Ruby on Rails, где объясняется процедура добавления Bootstrap в существующий проект Rails 5.

      Клонируйте репозиторий в директорию с именем rails-sidekiq:

      • git clone https://github.com/do-community/rails-bootstrap.git rails-sidekiq

      Перейдите в директорию rails-sidekiq:

      Для работы с кодом необходимо предварительно установить зависимости проекта, перечисленные в файле Gemfile. Также вам потребуется добавить в проект sidekiq gem для работы с Sidekiq и Redis.

      Откройте файл проекта Gemfile для редактирования, используя nano или другой предпочитаемый редактор:

      Добавьте зависимость в любое место в списке основных зависимостей проекта (над зависимостями разработки):

      ~/rails-sidekiq/Gemfile

      . . .
      # Reduces boot times through caching; required in config/boot.rb
      gem 'bootsnap', '>= 1.1.0', require: false
      gem 'sidekiq', '~>6.0.0'
      
      group :development, :test do
      . . .
      

      Сохраните и закройте файл после добавления зависимости.

      Используйте для установки зависимостей следующую команду:

      В результатах вы увидите, что зависимость redis также установлена как требование для sidekiq.

      Далее мы установим зависимости Yarn. Поскольку данный проект Rails 5 был модифицирован для обслуживания ресурсов с пакетом webpack, его зависимостями JavaScript теперь управляет Yarn. Это означает, что необходимо установить и проверить зависимости, указанные в файле проекта package.json.

      Используйте команду yarn install для установки этих зависимостей:

      Затем проведите миграцию базы данных:

      После завершения миграции вы можете протестировать приложение, чтобы убедиться, что оно работает ожидаемым образом. Запустите сервер в контексте локального пакета, используя следующую команду, если вы работаете на локальном компьютере:

      Если вы работаете на сервере разработки, вы можете запустить приложение с помощью следующей команды:

      • bundle exec rails s --binding=your_server_ip

      Перейдите на адрес localhost:3000 или http://your_server_ip:3000. Вы увидите следующую начальную страницу:

      Начальная страница приложения

      Чтобы создать новую акулу, нажмите кнопку Get Shark Info, после чего откроется путь sharks/index:

      Путь указателя акул

      Чтобы убедиться в работе приложения, добавим в него примеры данных. Нажмите New Shark. Вам будет предложено ввести имя пользователя (sammy) и пароль (shark) в связи с параметрами аутентификации проекта.

      На странице New Shark введите Great White в поле Name и Scary в поле Facts:

      Создание акулы

      Нажмите кнопку Create Shark для создания акулы. Когда акула будет создана, вы можете закрыть сервер, нажав CTRL+C.

      Вы установили необходимые зависимости для вашего проекта и протестировали его функционал. Теперь вы можете внести некоторые изменения в приложение Rails для работы с вашими ресурсами по находящимся под угрозой видам акул.

      Шаг 2 — Генерирование контроллера для ресурсов по находящимся под угрозой видам акул

      Чтобы работать с нашими ресурсами по находящимся под угрозой видам акул, мы добавим в приложение новую модель и контроллер, который будет определять, как информация по находящимся под угрозой видам акул будет выводиться пользователям. Наша конечная цель — дать пользователям возможность выгружать большие пакеты информации о находящихся под угрозой видах акул без блокировки функционала приложения и удалять эту информацию, когда она им больше не нужна.

      Прежде всего, мы создадим модель Endangered для наших находящихся под угрозой акул. Мы добавим в таблицу нашей базы данных поля строк для названий акул и категорий Международного союза охраны природы (МСОП), определяющих опасность для каждого из видов акул.

      Структура нашей модели будет соответствовать столбцам в файле CSV, который мы будем использовать для пакетной выгрузки данных. Этот файл находится в директории db, и вы можете проверить его содержимое с помощью следующей команды:

      Файл содержит список из 73 видов акул, находящихся под угрозой, и их статусов в МСОП: vu — опасность, en — угроза, cr — критическая угроза.

      Наша модель Endangered коррелирует с этими данными, позволяя создавать новые экземпляры Endangered из этого файла CSV. Создайте модель с помощью следующей команды:

      • rails generate model Endangered name:string iucn:string

      Сгенерируйте контроллер Endangered с помощью действия index:

      • rails generate controller endangered index

      Это даст нам исходную точку для создания функций нашего приложения, хотя нам понадобится добавить собственные методы в файл контроллера, сгенерированный для нас Rails.

      Откройте этот файл:

      • nano app/controllers/endangered_controller.rb

      Rails предоставляет нам каркас, который мы можем начать заполнять.

      Прежде всего нам нужно определить, какие маршруты нам потребуются для работы с нашими данными. Благодаря команде generate controller у нас имеется метод index, с которого мы можем начать. Он коррелирует с представлением index, где мы предоставим пользователям возможность выгрузки акул, находящихся под угрозой.

      Однако нам также нужны возможности и для случаев, когда пользователи уже выгрузили списки акул; в этом случае им не потребуется функция выгрузки. Нам потребуется какой-то способ, чтобы оценить количество уже существующих экземпляров класса Endangered, поскольку наличие нескольких экземпляров означает, что пакетная выгрузка уже выполнена.

      Для начала создадим частный метод set_endangered, который будет получать каждый экземпляр класса Endangered из базы данных. Добавьте в файл следующий код:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all
          end
      
      end
      

      Обратите внимание, что фильтр before_action обеспечивает установку значения @endangered только для маршрутов index и data, где мы обрабатываем данные по находящимся под угрозой видам акул.

      Добавьте следующий код в метод index, чтобы определить правильный путь для пользователей, посещающих эту часть приложения:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      . . .
      

      Если существует более 0 экземпляров нашего класса Endangered, мы перенаправляем пользователей на маршрут data, где они могут просматривать созданную ими информацию об акулах. В ином случае они перейдут к представлению index.

      Под методом index добавьте метод data, который будет коррелровать с представлением data:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data
        end
      . . .
      

      Затем мы добавим метод для обработки самой процедуры выгрузки данных. Мы назовем этот метод upload. Он будет вызывать класс рабочего Sidekiq и метод для выполнения выгрузки данных из файла CSV. На следующем шаге мы создадим определение для этого рабочего класса AddEndangeredWorker.

      Пока что добавьте в файл следующий код для вызова рабочего Sidekiq, который будет выполнять выгрузку:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def data
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      . . .
      

      Вызывая метод perform_async для класса AddEndangeredWorker с файлом CSV в качестве аргумента, этот код обеспечивает передачу в Redis данных об акулах и задания выгрузки. Заданные нами рабочие Sidekiq будут отслеживать очередь заданий и реагировать при появлении новых заданий.

      После вызова perform_async наш метод upload выполняет перенаправление на путь data, где пользователи смогут просматривать выгруженных акул.

      Далее мы добавим метод destroy для уничтожения данных. Добавьте следующий код после метода upload:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      . . .
      

      Как и метод upload, наш метод destroy включает вызов perform_async для класса RemoveEndangeredWorker, еще одного создаваемого нами рабочего Sidekiq. После вызова этот метод перенаправляет пользователей в корневую директорию приложения.

      Итоговый файл будет выглядеть примерно так:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all
          end
      
      end
      

      Сохраните и закройте файл после завершения редактирования.

      В заключение настройки маршрутов приложения мы изменим код в файле config/routes.rb, где хранятся декларации наших маршрутов.

      Откройте этот файл:

      Сейчас файл выглядит следующим образом:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Нам нужно будет обновить файл, чтобы добавить в него определенные в нашем контроллере маршруты: data, upload и destroy. Маршрут data будет соответствовать запросу GET на получение данных об акулах, а маршруты upload и destroy будут соответствовать запросам POST на выгрузку и уничтожение этих данных.

      Добавьте в файл следующий код для определения этих маршрутов:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'endangered/data', to: 'endangered#data'
        post 'endangered/upload', to: 'endangered#upload'
        post 'endangered/destroy', to: 'endangered#destroy'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Сохраните и закройте файл после завершения редактирования.

      Теперь у нас есть модель Endangered и контроллер, и мы можем перейти к определению рабочих классов Sidekiq.

      Шаг 3 — Определение рабочих Sidekiq

      Мы вызываем методы perform_async для рабочих Sidekiq в нашем контроллере, однако нам все еще нужно создать самих рабочих.

      Для начала создайте для рабочих директорию workers:

      Откройте файл для рабочего AddEndangeredWorker:

      • nano app/workers/add_endangered_worker.rb

      В этом файле мы добавим код, который позволит нам работать с данными в нашем файле CSV. Вначале добавьте код в файл, который будет создавать класс, включите в него библиотеку Ruby CSV и убедитесь, что этот класс функционирует как рабочий Sidekiq:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      Также мы добавим опцию retry: false, чтобы Sidekiq не пытался повторить выгрузку в случае ошибки.

      Далее добавьте код для функции perform:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform(csv_file)
          CSV.foreach(csv_file, headers: true) do |shark|
          Endangered.create(name: shark[0], iucn: shark[1])
        end
       end
      
      end
      

      Метод perform получает аргументы от метода perform_async, определенного в контроллере, поэтому очень важно обеспечить согласованность значений аргументов. Здесь мы передаем файл csv_file и определенную в контроллере переменную, а также используем метод foreach из библиотеки CSV для чтения значений в файле. Установка headers: true для этого цикла обеспечивает обработку первой строки в файле как строки заголовков.

      Затем блок считывает значения из файла в столбцы, заданные для нашей модели Endangered: name и iucn. При выполнении этого цикла будут созданы экземпляры Endangered для каждой из записей в нашем файле CSV.

      После завершения редактирования сохраните и закройте файл.

      Далее мы создадим рабочего для обработки удаления этих данных. Откройте файл для класса RemoveEndangeredWorker:

      • nano app/workers/remove_endangered_worker.rb

      Добавьте код для определения класса и убедитесь, что он использует библиотеку CSV и функционирует как рабочий Sidekiq:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      Затем добавьте метод perform для обработки уничтожения данных о находящихся под угрозой акулах:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform
          Endangered.destroy_all
        end
      
      end
      

      Метод perform вызывает destroy_all для класса Endangered, в результате чего все экземпляры этого класса удаляются из базы данных.

      Сохраните и закройте файл после завершения редактирования.

      Мы настроили рабочих и теперь можем перейти к созданию макета для представлений endangered и шаблонов для представлений index и data, чтобы пользователи могли выгружать и просматривать находящихся под угрозой акул.

      Шаг 4 — Добавление макетов и шаблонов представлений

      Чтобы пользователи смогли использовать свою информацию о находящихся под угрозой акулах, нам нужно обеспечить две вещи: макет представлений, определенных в контроллере endangered, и шаблоны для представлений index и data.

      Сейчас наше приложение использует общий макет app/views/layouts/application.html.erb, элемент навигации и макет для представлений sharks. Макет приложения проверяет наличие блока контента, что позволяет загружать другие макеты в зависимости от того, с какой частью приложения взаимодействует пользователь: для главного указателя они увидят один макет, а для представлений отдельных акул — другой.

      Мы можем изменть назначение макета sharks для представлений endangered, поскольку этот формат также подойдет для вывода массива данных об акулах.

      Скопируйте файл макета sharks для создания макета endangered:

      • cp app/views/layouts/sharks.html.erb app/views/layouts/endangered.html.erb

      Далее мы создадим шаблоны для представлений index и data.

      Откройте шаблон index:

      • nano app/views/endangered/index.html.erb

      Удалите базовый код и добавьте вместо него следующий код, который будет выводить пользователям информацию о находящихся под угрозой видах и предоставлять им возможность выгрузки информации о находящихся под угрозой акулах:

      ~/rails-sidekiq/app/views/endangered/index.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <br>
      
        <%= form_tag endangered_upload_path do %>
        <%= submit_tag "Import Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      Тег form_tag позволяет выгружать данные, указывая действие post для маршрута endangered_upload_path, заданного нами ранее для выгружаемых файлов. Кнопка отправки, созданная с помощью тега submit_tag, предлагает пользователям выполнить «Импорт находящихся под угрозой акул».

      В дополнение к этому коду мы указываем информацию о кодах МСОП, чтобы пользователи могли интерпретировать данные, которые они видят.

      Сохраните и закройте файл после завершения редактирования.

      Откройте файл для представления data:

      • nano app/views/endangered/data.html.erb

      Добавьте следующий код, который добавляет таблицу с данными о находящихся под угрозой видах акул:

      ~/rails-sidekiq/app/views/endangered/data.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <div class="table-responsive">
      <table class="table table-striped table-dark">
        <thead>
          <tr>
            <th>Name</th>
            <th>IUCN Status</th>
            <th colspan="3"></th>
          </tr>
        </thead>
      
        <tbody>
          <% @endangered.each do |shark| %>
            <tr>
              <td><%= shark.name %></td>
              <td><%= shark.iucn %></td>
            </tr>
          <% end %>
        </tbody>
      </table>
      </div>
      
      <br>
      
        <%= form_tag endangered_destroy_path do %>
        <%= submit_tag "Delete Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      Этот код содержит коды состояния МСОП и таблицу Bootstrap для выводимых данных. Выполняя цикл с переменной @endangered, мы выведем в таблицу названия и статусы МСОП для всех акул.

      Под таблицей располагается еще один набор тегов form_tags и submit_tags, которые используют метод post для пути destroy, предлагая пользователям возможность «Удалить находящихся под угрозой акул».

      Сохраните и закройте файл после завершения редактирования.

      В заключение мы внесем изменение в представление index, связанное с нашим контроллером home. Возможно вы помните, что это представление было задано как корневое для приложения в config/routes.rb.

      Откройте этот файл для редактирования:

      • nano app/views/home/index.html.erb

      Найдите столбец в строке Sharks are ancient​​​:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . .
              <div class="col-lg-6">
                  <h3>Sharks are ancient</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago.
                  </p>
              </div>
          </div>
      </div>
      

      Добавьте в файл следующий код:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . .
              <div class="col-lg-6">
                  <h3>Sharks are ancient and SOME are in danger</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago. Without our help, some could disappear soon.</p>
                  <p><%= button_to 'Which Sharks Are in Danger?', endangered_index_path, :method => :get,  :class => "btn btn-primary btn-sm"%>
                  </p>
              </div>
          </div>
      </div>
      

      Мы добавили призыв к действию для пользователей, желающих узнать больше о находящихся под угрозой акулах. Вначале мы разместили привлекающее внимание сообщение, а затем добавили помощник button_to, который отправляет запрос GET на наш маршрут endangered index, предоставляя пользователям доступ к этой части приложения. Там они смогут выгружать и просматривать данные о находящихся под угрозой акулах.

      Сохраните и закройте файл после завершения редактирования.

      Мы разместили код и теперь можем запустить приложение и выгрузить несколько акул!

      Шаг 5 — Запуск Sidekiq и тестирование приложения

      Перед запуском приложения нам нужно провести миграцию базы данных и запустить Sidekiq для активации наших рабочих. Redis уже должен работать на сервере, но для точности можно это проверить. Когда мы выполним эти задачи, мы будем готовы начинать тестирование приложения.

      Проверьте работу Redis:

      Результат будет выглядеть следующим образом:

      Output

      ● redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2019-11-12 20:37:13 UTC; 1 weeks 0 days ago

      Затем проведите миграцию базы данных:

      Теперь вы можете запустить Sidekiq в контексте текущего проекта с помощью команды bundle exec sidekiq:

      Вы увидите следующий вывод, указывающий, что Sidekiq готов к обработке заданий:

      Output

      m, `$b .ss, $$: .,d$ `$$P,d$P' .,md$P"' ,$$$$$b/md$$$P^' .d$$$$$$/$$$P' $$^' `"/$$$' ____ _ _ _ _ $: ,$$: / ___|(_) __| | ___| | _(_) __ _ `b :$$ ___ | |/ _` |/ _ |/ / |/ _` | $$: ___) | | (_| | __/ <| | (_| | $$ |____/|_|__,_|___|_|__|__, | .d$$ |_| 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Running in ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux] 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: See LICENSE and the LGPL-3.0 for licensing details. 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Booting Sidekiq 6.0.3 with redis options {:id=>"Sidekiq-server-PID-17621", :url=>nil} 2019-11-19T21:43:00.543Z pid=17621 tid=gpiqiesdl INFO: Starting processing, hit Ctrl-C to stop

      Откройте второе окно терминала, перейдите в директорию rails-sidekiq и запустите свой сервер приложений.

      Если вы запускаете приложение на локальном компьютере, используйте следующую команду:

      Если вы работаете с сервером разработки, запустите следующую команду:

      • bundle exec rails s --binding=your_server_ip

      Откройте в браузере адрес localhost:3000 или http://your_server_ip:3000. Вы увидите следующую начальную страницу:

      Домашняя директория приложения Sidekiq

      Нажмите кнопку Which Sharks Are in Danger?. Поскольку вы еще не выгрузили акул, находящихся под угрозой вымирания, сейчас откроется экран endangered index:

      Экран Endangered Index

      Нажмите Import Endangered Sharks для импорта акул. Вы увидите сообщение о состоянии, где будет указано, что акулы были импортированы:

      Начало импорта

      Также вы увидите начало импорта. Обновите страницу, чтобы увидеть таблицу целиком:

      Обновление таблицы

      Благодаря Sidekiq пакетная выгрузка акул, находящихся под угрозой вымирания, была проведена успешно без блокировки браузера и без помех для работы других приложений.

      Нажмите кнопку Home внизу страницы, чтобы вернуться на главную страницу приложения:

      Домашняя директория приложения Sidekiq

      Далее нажмите Which Sharks Are in Danger? еще раз. Поскольку вы уже выгрузили акул, после этого откроется представление data.

      Для тестирования функции удаления нажмите кнопку Delete Endangered Sharks под таблицей. Вы снова должны быть перенаправлены на главную страницу приложения. При нажатии Which Sharks Are in Danger? вы вернетесь к представлению index, где сможете снова выгрузить акул:

      Экран Endangered Index

      Теперь ваше приложение работает с рабочими Sidekiq, которые готовы обрабатывать задания и обеспечивать высокое качество обслуживания для пользователей вашего приложения.

      Заключение

      Мы создали работающее приложение Rails с активированным Sidekiq, позволяющее разгружать ресурсоемкие операции в очередь заданий под управлением Sidekiq при поддержке Redis. Это позволит повысить скорость и функциональность разрабатываемого сайта.

      Если вы хотите узнать больше о Sidekiq, начните с документации.

      Дополнительную информацию о Redis можно найти в нашей библиотеке ресурсов по Redis. Дополнительную информацию о запуске управляемого кластера Redis в инфраструктуре DigitalOcean можно найти в документации по продукту.



      Source link

      Como adicionar o Sidekiq e o Redis a um aplicativo Ruby on Rails


      Introdução

      Ao desenvolver um aplicativo Ruby on Rails, você pode se deparar com tarefas de aplicativos que devem ser executadas de maneira assíncrona. O processamento de dados, envio de e-mails em lote, ou a interação com APIs externas são todos exemplos de trabalho que podem ser feitos de maneira assíncrona com o background jobs. O uso de jobs em segundo plano pode melhorar o desempenho de seu aplicativo, descarregando tarefas potencialmente demoradas em uma fila de processamento em segundo plano, liberando o ciclo de solicitação/resposta original.

      O Sidekiq é uma das frameworks mais amplamente utilizadas em jobs de segundo plano que você pode implementar em um aplicativo Rails. Ele é apoiado pelo Redis, um armazenamento de valores-chave dentro da memória conhecido pela sua flexibilidade e desempenho. O Sidekiq utiliza o Redis como um armazenamento de gerenciamento de tarefas para processar milhares de tarefas por segundo.

      Neste tutorial, você adicionará o Redis e o Sidekiq a um aplicativo existente do Rails. Você criará um conjunto de classes e métodos de trabalho do Sidekiq para lidar com:

      • Um upload em lote de informações de tubarões ameaçados de extinção para o banco de dados do aplicativo de um arquivo CSV no repositório de projeto.
      • A remoção desses dados.

      Quando terminar, terá um aplicativo de demonstração que utilizará trabalhadores e trabalhos para processar tarefas de maneira assíncrona. Esta será uma boa base para que você adicione trabalhadores e trabalhos ao seu próprio aplicativo, usando este tutorial como um ponto de partida.

      Pré-requisitos

      Para seguir este tutorial, você vai precisar do seguinte:

      Passo 1 — Clonando o projeto e instalando dependências

      Nosso primeiro passo será clonar o repositório de rails-bootstrap da conta do GitHub da Comunidade da DigitalOcean. Esse repositório inclui o código da configuração descrita em Como adicionar o Bootstrap em um aplicativo Ruby on Rails, que explica como adicionar o Bootstrap a um projeto Rails 5 existente.

      Clone o repositório em um diretório chamado rails-sidekiq:

      • git clone https://github.com/do-community/rails-bootstrap.git rails-sidekiq

      Navegue até o diretório rails-sidekiq:

      Para trabalhar com o código, primeiro será necessário instalar as dependências do projeto, que estão listadas em seu Gemfile. Você também precisará adicionar o sidekiq gem ao projeto para trabalhar com o Sidekiq e o Redis.

      Abra o Gemfile do projeto para editá-lo usando o nano ou seu editor favorito:

      Adicione a gem em qualquer lugar das dependências principais do projeto (acima das dependências de desenvolvimento):

      ~/rails-sidekiq/Gemfile

      . . .
      # Reduces boot times through caching; required in config/boot.rb
      gem 'bootsnap', '>= 1.1.0', require: false
      gem 'sidekiq', '~>6.0.0'
      
      group :development, :test do
      . . .
      

      Salve e feche o arquivo quando terminar de adicionar o gem.

      Use o seguinte comando para instalar os gems:

      Você verá na saída que o redis gem também está instalado como um requisito para o sidekiq.

      Em seguida, você instalará suas dependências do Yarn. Como esse projeto Rails 5 foi modificado para atender ativos com o webpack, as dependências de JavaScript dele são gerenciadas agora pelo Yarn. Isso significa que é necessário instalar e verificar as dependências listadas no arquivo do projeto package.json.

      Execute o yarn install para instalar essas dependências:

      Em seguida, execute seu banco de dados de migrações:

      Assim que suas migrações terminarem, teste o aplicativo para garantir que ele esteja funcionando como esperado. Caso esteja trabalhando localmente, inicie seu servidor no contexto do seu pacote local com o seguinte comando:

      Caso esteja trabalhando em um servidor de desenvolvimento, inicie o aplicativo com:

      • bundle exec rails s --binding=your_server_ip

      Navegue até o localhost:3000 ou http://your_server_ip:3000. Você verá a seguinte página inicial:

      Página inicial do aplicativo

      Para criar um novo tubarão, clique no botão Get Shark Info, que levará você até a rota sharks/index:

      Rota do Índice de Tubarões

      Para verificar se o aplicativo está funcionando, podemos adicionar algumas informações de demonstração a ele. Clique em New Shark. Será solicitado que coloque um nome de usuário (sammy) e senha (shark), graças às configurações de autenticação do projeto.

      Na página New Shark, digite “Great White” no campo Name e “Scary” no campo Facts.

      Criar Tubarão

      Clique no botão Create Shark para criar o tubarão. Assim que ver que seu tubarão foi criado, encerre o servidor com CTRL+C.

      Você instalou as dependências necessárias para seu projeto e testou sua funcionalidade. Em seguida, você pode fazer algumas alterações no aplicativo Rails para trabalhar com seus recursos de tubarões ameaçados de extinção.

      Passo 2 — Gerando um controlador para recursos de tubarões ameaçados de extinção

      Para trabalhar com nossos recursos de tubarões ameaçados de extinção, adicionaremos um novo modelo ao aplicativo e um controlador que controlará como as informações sobre tubarões ameaçados de extinção serão apresentadas aos usuários. Nosso objetivo final é tornar possível que os usuários enviem um lote grande de informações sobre tubarões ameaçados de extinção sem bloquear a funcionalidade geral do nosso aplicativo e excluírem essas informações quando não precisarem mais delas.

      Primeiro, vamos criar um modelo Endangered para nossos tubarões ameaçados de extinção. Vamos incluir um campo string em nossa tabela de banco de dados para o nome do tubarão e outro campo string para as categorias da União Internacional para a Conservação da Natureza (IUCN), que determina o grau em que cada tubarão está em risco.

      Por fim, nossa estrutura de modelo corresponderá às colunas do arquivo CSV que usaremos para criar nosso upload do lote. Este arquivo está localizado no diretório db e você pode verificar seu conteúdo com o seguinte comando:

      O arquivo contém uma lista de 73 tubarões ameaçados de extinção e seus status de IUCN – vu para vulneráveis, en para ameaçados de extinção e cr para criticamente ameaçados de extinção.

      Nosso modelo Endangered se correlacionará com esses dados, permitindo-nos criar novas instâncias de Endangered a partir deste arquivo CSV. Crie o modelo com o seguinte comando:

      • rails generate model Endangered name:string iucn:string

      Em seguida, gere um controlador Endangered com uma ação index:

      • rails generate controller endangered index

      Isso nos dará um ponto de partida para desenvolver a funcionalidade do nosso aplicativo, embora também seja necessário adicionar métodos personalizados ao arquivo do controlador que o Rails gerou para nós.

      Abra aquele arquivo agora:

      • nano app/controllers/endangered_controller.rb

      O Rails nos forneceu um rascunho que podemos começar a preencher.

      Primeiro, vamos precisar determinar quais rotas precisamos trabalhar com nossos dados. Graças ao comando generate controller, temos um método index para começar. Isso se correlacionará a uma visualização do index, onde apresentaremos usuários com a opção de fazer o upload de tubarões ameaçados de extinção.

      No entanto, também queremos lidar com casos onde os usuários podem já ter feito upload dos tubarões; eles não precisarão de uma opção de upload neste caso. De algum modo precisaremos avaliar quantas instâncias da classe Endangered já existem, uma vez que mais de uma indica que o upload do lote já ocorreu.

      Vamos começar criando um método private set_endangered que capturará cada instância de nossa classe Endangered a partir do banco de dados. Adicione o código a seguir ao arquivo:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all
          end
      
      end
      

      Note que o filtro before_action garantirá que o valor @endangered seja definido apenas para as rotas index e data, que serão as rotas onde lidaremos com os dados dos tubarões ameaçados de extinção.

      Em seguida, adicione o seguinte código ao método index para determinar a rota correta para usuários visitando esta parte do aplicativo:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      . . .
      

      Caso não exista nenhuma instância de nossa classe Endangered, redirecionaremos os usuários para a rota data, onde podem visualizar informações sobre os tubarões que eles criaram. Caso contrário, eles visualizarão o index.

      Em seguida, abaixo do método index, adicione um método data, que se correlacionará a uma visualização do método data:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data
        end
      . . .
      

      Em seguida, adicionaremos um método para lidar com o upload de dados propriamente dito. Vamos chamar este método de upload e chamaremos uma classe trabalhadora e um método Sidekiq para realizar o upload de dados do arquivo CSV. Criaremos a definição para essa classe trabalhadora, AddEndangeredWorker, no próximo passo.

      Por enquanto, adicione o seguinte código ao arquivo para fazer o trabalhador do Sidekiq realizar o upload:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def data
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      . . .
      

      Ao chamar o método perform_async da classe AddEndangeredWorker usando o arquivo CSV como um argumento, este código garante que os dados do tubarão e o trabalho de upload sejam passados para o Redis. Os trabalhadores do Sidekiq que vamos configurar monitoram a fila de trabalho e reagirão quando novos trabalhos surgirem.

      Após chamar o perform_async, nosso método de upload redireciona para o caminho data, onde os usuários poderão ver os tubarões carregados.

      Em seguida, adicionaremos um método destroy para destruir os dados. Adicione o seguinte código abaixo do método do upload:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . .
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      . . .
      

      Da mesma forma que nosso método de upload, nosso método destroy inclui uma chamada do perform_async de uma classe RemoveEndangeredWorker — o outro trabalhador Sidekiq que vamos criar. Após chamar este método, ele redireciona os usuários para o caminho do aplicativo raiz.

      O arquivo final se parecerá com este:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all
          end
      
      end
      

      Salve e feche o arquivo quando você terminar a edição.

      Como passo final na consolidação das rotas do nosso aplicativo, vamos modificar o código em config/routes.rb, o arquivo onde ficam nossas declarações de rota.

      Abra aquele arquivo agora:

      O arquivo se parece com esse:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Vamos precisar atualizar o arquivo para incluir as rotas que definimos em nosso controlador: data, upload e destroy. Nossa rota de data corresponderá a uma solicitação GET para recuperar os dados do tubarão, enquanto nossas rotas de upload e destroy mapearão as solicitações POST, que farão o upload e a destruição desses dados.

      Adicione o código a seguir ao arquivo para definir essas rotas:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'endangered/data', to: 'endangered#data'
        post 'endangered/upload', to: 'endangered#upload'
        post 'endangered/destroy', to: 'endangered#destroy'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Salve e feche o arquivo quando você terminar a edição.

      Com seu modelo e controlador Endangered em funcionamento, continue para definir suas classes de trabalhadores do Sidekiq.

      Passo 3 — Definindo os trabalhadores do Sidekiq

      Chamamos os métodos do perform_async nos trabalhadores do Sidekiq em nosso controlador, mas ainda precisamos criar os trabalhadores em si.

      Primeiro, crie um diretório workers para os trabalhadores:

      Abra um arquivo para o trabalhador AddEndangeredWorker:

      • nano app/workers/add_endangered_worker.rb

      Neste arquivo, adicionaremos códigos que nos permitirá trabalhar com os dados em nosso arquivo CSV. Primeiro, adicione códigos ao arquivo que criarão a classe, inclua a biblioteca Ruby CSV e certifique-se de que essa classe funcione como um trabalhador Sidekiq:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      Também incluiremos a opção retry: false para garantir que o Sidekiq não tente fazer o upload novamente em caso de falha.

      Em seguida, adicione o código para a função perform:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform(csv_file)
          CSV.foreach(csv_file, headers: true) do |shark|
          Endangered.create(name: shark[0], iucn: shark[1])
        end
       end
      
      end
      

      O método perform recebe argumentos do método perform_async definido no controlador, por este motivo, é importante que os valores do argumento estejam alinhados. Aqui, passamos a csv_file, a variável que definimos no controlador, e usamos o método foreach da biblioteca CSV para ler os valores no arquivo. Definir headers: true para este loop garante que a primeira linha do arquivo seja tratada como uma linha de cabeçalhos.

      Então, o bloco lê os valores do arquivo nas colunas que definimos para nosso modelo Endangered: name e iucn. Executar este loop criará instâncias Endangered para cada uma das entradas em nosso arquivo CSV.

      Assim que terminar a edição, salve e feche o arquivo.

      Em seguida, criaremos um trabalhador para lidar com a exclusão desses dados. Abra um arquivo para a classe RemoveEndangeredWorker:

      • nano app/workers/remove_endangered_worker.rb

      Adicione o código a seguir para definir a classe, e para garantir que ela utilize a biblioteca e as funções CSV como um trabalhador Sidekiq:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      Em seguida, adicione um método perform para lidar com a destruição dos dados dos tubarões ameaçados de extinção:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform
          Endangered.destroy_all
        end
      
      end
      

      O método perform chama a função destroy_all na classe Endangered, que removerá todas as instâncias da classe a partir do banco de dados.

      Salve e feche o arquivo quando você terminar a edição.

      Com seus trabalhadores em funcionamento, continue para a criação de um layout para suas visualizações de endangered e a criação de modelos para a visualização de seus index e data, de modo que os usuários possam fazer upload e visualizar tubarões ameaçados de extinção.

      Passo 4 — Adicionando layouts e modelos de visualização

      Para que os usuários aproveitem suas informações de tubarões ameaçados de extinção, precisaremos abordar duas coisas: o layout para as visualizações definidas em nosso controlador endangered e os modelos de visualização para as visualizações de index e de data.

      Atualmente, nosso aplicativo utiliza um layout em todo o aplicativo, localizado em app/views/layouts/application.html.erb, uma navegação parcial e um layout para visualizações de sharks. O layout do aplicativo verifica se há um bloco de conteúdo que nos permita carregar diferentes layouts com base em qual parte do aplicativo nosso usuário se encontra: para a home index, os usuários verão um layout, e para quaisquer visualizações relacionadas a tubarões individuais, eles verão outro layout.

      Podemos reaproveitar o layout sharks para nossas visualizações endangered, uma vez que este formato também funcionará para a apresentação de dados de tubarões em massa.

      Copie o arquivo de layout de sharks para criar um layout de endangered:

      • cp app/views/layouts/sharks.html.erb app/views/layouts/endangered.html.erb

      Em seguida, vamos trabalhar na criação dos modelos de visualização para nossas visualizações de index e de data.

      Abra o modelo index primeiro:

      • nano app/views/endangered/index.html.erb

      Exclua o código boilerplate e adicione o código a seguir, o qual dará informações gerais aos usuários sobre as categorias ameaçados de extinção e os apresentará com a opção de fazer o upload das informações sobre eles:

      ~/rails-sidekiq/app/views/endangered/index.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <br>
      
        <%= form_tag endangered_upload_path do %>
        <%= submit_tag "Import Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      Uma form_tag torna o upload de dados possível, apontando uma ação posterior para a endangered_upload_path — a rota que definimos para nossos uploads. Um botão de enviar, criado com o submit_tag, solicita que os usuários façam o "Import Endangered Sharks​".

      Além deste código, incluímos algumas informações gerais sobre os códigos ICUN, de modo que os usuários possam interpretar os dados que eles verão.

      Salve e feche o arquivo quando você terminar a edição.

      Em seguida, abra um arquivo para a visualização de data:

      • nano app/views/endangered/data.html.erb

      Adicione o código a seguir, que adicionará uma tabela com os dados de tubarões ameaçados de extinção:

      ~/rails-sidekiq/app/views/endangered/data.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <div class="table-responsive">
      <table class="table table-striped table-dark">
        <thead>
          <tr>
            <th>Name</th>
            <th>IUCN Status</th>
            <th colspan="3"></th>
          </tr>
        </thead>
      
        <tbody>
          <% @endangered.each do |shark| %>
            <tr>
              <td><%= shark.name %></td>
              <td><%= shark.iucn %></td>
            </tr>
          <% end %>
        </tbody>
      </table>
      </div>
      
      <br>
      
        <%= form_tag endangered_destroy_path do %>
        <%= submit_tag "Delete Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      Esse código inclui os códigos de status da ICUN novamente e uma tabela de Inicialização para os dados produzidos. Ao fazer loop através de nossa variável @endangered, produziremos o nome e o status de ICUN de cada tubarão para a tabela.

      Abaixo da tabela, temos outro conjunto de form_tags e de submit_tags que foram enviados para o caminho destroy, oferecendo aos usuários a opção "Delete Endangered Sharks".

      Salve e feche o arquivo quando você terminar a edição.

      A última modificação que vamos fazer às visualizações será feita na visualização de index associada ao nosso controlador home. Você deve se lembrar de que essa visualização está definida como a raiz do aplicativo em config/routes.rb.

      Abra este arquivo para edição:

      • nano app/views/home/index.html.erb

      Encontre a coluna na linha que afirma que Sharks are ancient​​​:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . .
              <div class="col-lg-6">
                  <h3>Sharks are ancient</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago.
                  </p>
              </div>
          </div>
      </div>
      

      Adicione o código a seguir ao arquivo:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . .
              <div class="col-lg-6">
                  <h3>Sharks are ancient and SOME are in danger</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago. Without our help, some could disappear soon.</p>
                  <p><%= button_to 'Which Sharks Are in Danger?', endangered_index_path, :method => :get,  :class => "btn btn-primary btn-sm"%>
                  </p>
              </div>
          </div>
      </div>
      

      Incluímos uma chamada de ação para os usuários aprenderem mais sobre os tubarões ameaçados de extinção, primeiramente compartilhando uma mensagem importante e, em seguida, adicionando um auxiliar button_to que envia uma solicitação GET para nossa rota de endangered index, dando acesso a essa parte do aplicativo. A partir daí, eles poderão fazer o upload e visualizar informações sobre tubarões ameaçados de extinção.

      Salve e feche o arquivo quando você terminar a edição.

      Com seu código funcionando, você está pronto para inicializar o aplicativo e fazer o upload de alguns tubarões!

      Passo 5 — Inicializando o Sidekiq e testando o aplicativo

      Antes de inicializar o aplicativo, precisaremos executar as migrações em nosso banco de dados e iniciar o Sidekiq para habilitar nossos trabalhadores. O Redis já deve estar em execução no servidor, mas podemos verificar isso para termos certeza. Com tudo isso funcionando, estaremos prontos para testar o aplicativo.

      Primeiro, verifique se o Redis está funcionando:

      Deverá ver um resultado como o seguinte:

      Output

      ● redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2019-11-12 20:37:13 UTC; 1 weeks 0 days ago

      Em seguida, execute seu banco de dados de migrações:

      Agora, você pode iniciar o Sidekiq no contexto do seu pacote atual do projeto, usando o comando bundle exec sidekiq​​​:

      Você verá um resultado como este, indicando que o Sidekiq está pronto para processar trabalhos:

      Output

      m, `$b .ss, $$: .,d$ `$$P,d$P' .,md$P"' ,$$$$$b/md$$$P^' .d$$$$$$/$$$P' $$^' `"/$$$' ____ _ _ _ _ $: ,$$: / ___|(_) __| | ___| | _(_) __ _ `b :$$ ___ | |/ _` |/ _ |/ / |/ _` | $$: ___) | | (_| | __/ <| | (_| | $$ |____/|_|__,_|___|_|__|__, | .d$$ |_| 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Running in ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux] 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: See LICENSE and the LGPL-3.0 for licensing details. 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Booting Sidekiq 6.0.3 with redis options {:id=>"Sidekiq-server-PID-17621", :url=>nil} 2019-11-19T21:43:00.543Z pid=17621 tid=gpiqiesdl INFO: Starting processing, hit Ctrl-C to stop

      Abra uma segunda janela de terminal, navegue para o diretório rails-sidekiq e inicialize seu servidor do aplicativo.

      Caso esteja executando o aplicativo localmente, use o seguinte comando:

      Caso esteja trabalhando com um servidor de desenvolvimento, execute o seguinte:

      • bundle exec rails s --binding=your_server_ip

      Navegue para o localhost:3000 ou http://your_server_ip:3000 no navegador. Você verá a seguinte página inicial:

      Página inicial do App Sidekiq

      Clique no botão Which Sharks Are in Danger? [Quais tubarões estão em perigo?] . Como não fez upload de nenhum tubarão ameaçado de extinção, isso levará você até a visualização de endangered index:

      Exibição do índice Endangered [Em perigo]

      Clique em Import Endangered Sharks para importar os tubarões. Você verá uma mensagem de status informando que os tubarões foram importados:

      Iniciar importação

      Você verá também o início da importação. Atualize sua página para ver a tabela inteira:

      Atualizar tabela

      Graças ao Sidekiq, o upload de nosso lote grande de tubarões em perigo foi bem-sucedido, sem bloquear o navegador ou interferir com outras funcionalidades do aplicativo.

      Clique no botão Home, no final da página, para voltar à página principal do aplicativo:

      Página inicial do App Sidekiq

      A partir daqui, clique em Which Sharks Are in Danger? novamente. Isso levará você diretamente para a visualização de data, uma vez que você já fez o upload dos tubarões.

      Para testar a funcionalidade de exclusão, clique no botão Delete Endangered Sharks​​​ abaixo da tabela. Você deve ser redirecionado para a página inicial do aplicativo novamente. Clicando em Which Sharks Are in Danger? uma última vez levará você de volta para a visualização do index, onde terá a opção de fazer o upload dos tubarões novamente:

      Exibição do índice Endangered [Em perigo]

      Seu aplicativo agora está funcionando com os trabalhadores Sidekiq, que estão prontos para processar trabalhos e garantir que os usuários tenham uma boa experiência ao trabalhar com seu aplicativo.

      Conclusão

      Agora, você tem um aplicativo Rails em funcionamento com o Sidekiq habilitado, o que permitirá que você descarregue operações dispendiosas em uma fila de trabalho gerenciada pelo Sidekiq e apoiada pelo Redis. Isso permitirá que você melhore a velocidade e a funcionalidade do seu site à medida que desenvolve.

      Caso queira aprender mais sobre o Sidekiq, os docs são um bom lugar para começar.

      Para aprender mais sobre o Redis, confira nossa biblioteca dos recursos do Redis. Você também pode aprender mais sobre a execução de um cluster gerenciado do Redis na DigitalOcean, conferindo a documentação do produto.



      Source link

      How To Add Sidekiq and Redis to a Ruby on Rails Application


      Introduction

      When developing a Ruby on Rails application, you may find you have application tasks that should be performed asynchronously. Processing data, sending batch emails, or interacting with external APIs are all examples of work that can be done asynchronously with background jobs. Using background jobs can improve your application’s performance by offloading potentially time-intensive tasks to a background processing queue, freeing up the original request/response cycle.

      Sidekiq is one of the more widely used background job frameworks that you can implement in a Rails application. It is backed by Redis, an in-memory key-value store known for its flexibility and performance. Sidekiq uses Redis as a job management store to process thousands of jobs per second.

      In this tutorial, you will add Redis and Sidekiq to an existing Rails application. You will create a set of Sidekiq worker classes and methods to handle:

      • A batch upload of endangered shark information to the application database from a CSV file in the project repository.
      • The removal of this data.

      When you are finished, you will have a demo application that uses workers and jobs to process tasks asynchronously. This will be a good foundation for you to add workers and jobs to your own application, using this tutorial as a jumping off point.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Cloning the Project and Installing Dependencies

      Our first step will be to clone the rails-bootstrap repository from the DigitalOcean Community GitHub account. This repository includes the code from the setup described in How To Add Bootstrap to a Ruby on Rails Application, which explains how to add Bootstrap to an existing Rails 5 project.

      Clone the repository into a directory called rails-sidekiq:

      • git clone https://github.com/do-community/rails-bootstrap.git rails-sidekiq

      Navigate to the rails-sidekiq directory:

      In order to work with the code, you will first need to install the project’s dependencies, which are listed in its Gemfile. You will also need to add the sidekiq gem to the project to work with Sidekiq and Redis.

      Open the project’s Gemfile for editing, using nano or your favorite editor:

      Add the gem anywhere in the main project dependencies (above development dependencies):

      ~/rails-sidekiq/Gemfile

      . . . 
      # Reduces boot times through caching; required in config/boot.rb
      gem 'bootsnap', '>= 1.1.0', require: false
      gem 'sidekiq', '~>6.0.0'
      
      group :development, :test do
      . . .
      

      Save and close the file when you are finished adding the gem.

      Use the following command to install the gems:

      You will see in the output that the redis gem is also installed as a requirement for sidekiq.

      Next, you will install your Yarn dependencies. Because this Rails 5 project has been modified to serve assets with webpack, its JavaScript dependencies are now managed by Yarn. This means that it’s necessary to install and verify the dependencies listed in the project’s package.json file.

      Run yarn install to install these dependencies:

      Next, run your database migrations:

      Once your migrations have finished, you can test the application to ensure that it is working as expected. Start your server in the context of your local bundle with the following command if you are working locally:

      If you are working on a development server, you can start the application with:

      • bundle exec rails s --binding=your_server_ip

      Navigate to localhost:3000 or http://your_server_ip:3000. You will see the following landing page:

      Application Landing Page

      To create a new shark, click on the Get Shark Info button, which will take you to the sharks/index route:

      Sharks Index Route

      To verify that the application is working, we can add some demo information to it. Click on New Shark. You will be prompted for a username (sammy) and password (shark), thanks to the project’s authentication settings.

      On the New Shark page, input “Great White” into the Name field and “Scary” into the Facts field:

      Shark Create

      Click on the Create Shark button to create the shark. Once you see that your shark has been created, you can kill the server with CTRL+C.

      You have now installed the necessary dependencies for your project and tested its functionality. Next, you can make a few changes to the Rails application to work with your endangered sharks resources.

      Step 2 — Generating a Controller for Endangered Shark Resources

      To work with our endangered shark resources, we will add a new model to the application and a controller that will control how information about endangered sharks is presented to users. Our ultimate goal is to make it possible for users to upload a large batch of information about endangered sharks without blocking our application’s overall functionality, and to delete that information when they no longer need it.

      First, let’s create an Endangered model for our endangered sharks. We’ll include a string field in our database table for the shark name, and another string field for the International Union for the Conservation of Nature (IUCN) categories that determine the degree to which each shark is at risk.

      Ultimately, our model structure will match the columns in the CSV file that we will use to create our batch upload. This file is located in the db directory, and you can check its contents with the following command:

      The file contains a list of 73 endangered sharks and their IUCN statuses - vu for vulnerable, en for endangered, and cr for critically endangered.

      Our Endangered model will correlate with this data, allowing us to create new Endangered instances from this CSV file. Create the model with the following command:

      • rails generate model Endangered name:string iucn:string

      Next, generate an Endangered controller with an index action:

      • rails generate controller endangered index

      This will give us a starting point to build out our application’s functionality, though we will also need to add custom methods to the controller file that Rails has generated for us.

      Open that file now:

      • nano app/controllers/endangered_controller.rb

      Rails has provided us with a skeletal outline that we can begin to fill in.

      First, we’ll need to determine what routes we require to work with our data. Thanks to the generate controller command, we have an index method to begin with. This will correlate to an index view, where we will present users with the option to upload endangered sharks.

      However, we will also want to deal with cases where users may have already uploaded the sharks; they will not need an upload option in this case. We will somehow need to assess how many instances of the Endangered class already exist, since more than one indicates that the batch upload has already occurred.

      Let’s start by creating a set_endangered private method that will grab each instance of our Endangered class from the database. Add the following code to the file:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all 
          end
      
      end
      

      Note that the before_action filter will ensure that the value of @endangered is only set for the index and data routes, which will be where we handle the endangered shark data.

      Next, add the following code to the index method to determine the correct path for users visiting this part of the application:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      . . . 
      

      If there are more than 0 instances of our Endangered class, we will redirect users to the data route, where they can view information about the sharks they’ve created. Otherwise, they will see the index view.

      Next, below the index method, add a data method, which will correlate to a data view:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . . 
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data 
        end
      . . .
      

      Next, we will add a method to handle the data upload itself. We’ll call this method upload, and it will call a Sidekiq worker class and method to perform the data upload from the CSV file. We will create the definition for this worker class, AddEndangeredWorker, in the next step.

      For now, add the following code to the file to call the Sidekiq worker to perform the upload:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . . 
        def data 
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      . . .
      

      By calling the perform_async method on the AddEndangeredWorker class, using the CSV file as an argument, this code ensures that the shark data and upload job get passed to Redis. The Sidekiq workers that we will set up monitor the job queue and will respond when new jobs arise.

      After calling perform_async, our upload method redirects to the data path, where users will be able to see the uploaded sharks.

      Next, we’ll add a destroy method to destroy the data. Add the following code below the upload method:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      . . . 
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      . . . 
      

      Like our upload method, our destroy method includes a perform_async call on a RemoveEndangeredWorker class – the other Sidekiq worker that we will create. After calling this method, it redirects users to the root application path.

      The finished file will look like this:

      ~/rails-sidekiq/app/controllers/endangered_controller.rb

      class EndangeredController < ApplicationController
        before_action :set_endangered, only: [:index, :data]
      
        def index          
          if @endangered.length > 0
            redirect_to endangered_data_path
          else
            render 'index'
          end
        end
      
        def data 
        end
      
        def upload
          csv_file = File.join Rails.root, 'db', 'sharks.csv'   
          AddEndangeredWorker.perform_async(csv_file)
          redirect_to endangered_data_path, notice: 'Endangered sharks have been uploaded!'
        end
      
        def destroy
          RemoveEndangeredWorker.perform_async
          redirect_to root_path
        end
      
        private
      
          def set_endangered
            @endangered = Endangered.all 
          end 
      
      end
      

      Save and close the file when you are finished editing.

      As a final step in solidifying our application’s routes, we will modify the code in config/routes.rb, the file where our route declarations live.

      Open that file now:

      The file currently looks like this:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      We will need to update the file to include the routes that we’ve defined in our controller: data, upload, and destroy. Our data route will match with a GET request to retrieve the shark data, while our upload and destroy routes will map to POST requests that upload and destroy that data.

      Add the following code to the file to define these routes:

      ~/rails-sidekiq/config/routes.rb

      Rails.application.routes.draw do
        get 'endangered/index'
        get 'endangered/data', to: 'endangered#data'
        post 'endangered/upload', to: 'endangered#upload'
        post 'endangered/destroy', to: 'endangered#destroy'
        get 'home/index'
        resources :sharks do
                resources :posts
        end
        root 'home#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Save and close the file when you are finished editing.

      With your Endangered model and controller in place, you can now move on to defining your Sidekiq worker classes.

      Step 3 — Defining Sidekiq Workers

      We have called perform_async methods on our Sidekiq workers in our controller, but we still need to create the workers themselves.

      First, create a workers directory for the workers:

      Open a file for the AddEndangeredWorker worker:

      • nano app/workers/add_endangered_worker.rb

      In this file, we will add code that will allow us to work with the data in our CSV file. First, add code to the file that will create the class, include the Ruby CSV library, and ensure that this class functions as a Sidekiq Worker:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      We’re also including the retry: false option to ensure that Sidekiq does not retry the upload in the case of failure.

      Next, add the code for the perform function:

      ~/rails-sidekiq/app/workers/add_endangered_worker.rb

      class AddEndangeredWorker
        require 'csv'
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform(csv_file)
          CSV.foreach(csv_file, headers: true) do |shark|
          Endangered.create(name: shark[0], iucn: shark[1])
        end
       end
      
      end
      

      The perform method receives arguments from the perform_async method defined in the controller, so it’s important that the argument values are aligned. Here, we pass in csv_file, the variable we defined in the controller, and we use the foreach method from the CSV library to read the values in the file. Setting headers: true for this loop ensures that the first row of the file is treated as a row of headers.

      The block then reads the values from the file into the columns we set for our Endangered model: name and iucn. Running this loop will create Endangered instances for each of the entries in our CSV file.

      Once you have finished editing, save and close the file.

      Next, we will create a worker to handle deleting this data. Open a file for the RemoveEndangeredWorker class:

      • nano app/workers/remove_endangered_worker.rb

      Add the code to define the class, and to ensure that it uses the CSV library and functions as a Sidekiq Worker:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
      end
      

      Next, add a perform method to handle the destruction of the endangered shark data:

      ~/rails-sidekiq/app/workers/remove_endangered_worker.rb

      class RemoveEndangeredWorker
        include Sidekiq::Worker
        sidekiq_options retry: false
      
        def perform
          Endangered.destroy_all
        end
      
      end
      

      The perform method calls destroy_all on the Endangered class, which will remove all instances of the class from the database.

      Save and close the file when you are finished editing.

      With your workers in place, you can move on to creating a layout for your endangered views, and templates for your index and data views, so that users can upload and view endangered sharks.

      Step 4 — Adding Layouts and View Templates

      In order for users to enjoy their endangered shark information, we will need to address two things: the layout for the views defined in our endangered controller, and the view templates for the index and data views.

      Currently, our application makes use of an application-wide layout, located at app/views/layouts/application.html.erb, a navigation partial, and a layout for sharks views. The application layout checks for a content block, which allows us to load different layouts based on which part of the application our user is engaging with: for the home index page, they will see one layout, and for any views relating to individual sharks, they will see another.

      We can repurpose the sharks layout for our endangered views since this format will also work for presenting shark data in bulk.

      Copy the sharks layout file over to create an endangered layout:

      • cp app/views/layouts/sharks.html.erb app/views/layouts/endangered.html.erb

      Next, we’ll work on creating the view templates for our index and data views.

      Open the index template first:

      • nano app/views/endangered/index.html.erb

      Delete the boilerplate code and add the following code instead, which will give users some general information about the endangered categories and present them with the option to upload information about endangered sharks:

      ~/rails-sidekiq/app/views/endangered/index.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <br>
      
        <%= form_tag endangered_upload_path do %>
        <%= submit_tag "Import Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      A form_tag makes the data upload possible by pointing a post action to the endangered_upload_path – the route we defined for our uploads. A submit button, created with the submit_tag, prompts users to "Import Endangered Sharks".

      In addition to this code, we’ve included some general information about ICUN codes, so that users can interpret the data they will see.

      Save and close the file when you are finished editing.

      Next, open a file for the data view:

      • nano app/views/endangered/data.html.erb

      Add the following code, which will add a table with the endangered shark data:

      ~/rails-sidekiq/app/views/endangered/data.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Endangered Sharks</h1>
      
      <p>International Union for Conservation of Nature (ICUN) statuses: <b>vu:</b> Vulnerable, <b>en:</b> Endangered, <b>cr:</b> Critically Endangered </p>
      
      <div class="table-responsive">
      <table class="table table-striped table-dark">
        <thead>
          <tr>
            <th>Name</th>
            <th>IUCN Status</th>
            <th colspan="3"></th>
          </tr>
        </thead>
      
        <tbody>
          <% @endangered.each do |shark| %>
            <tr>
              <td><%= shark.name %></td>
              <td><%= shark.iucn %></td>
            </tr>
          <% end %>
        </tbody>
      </table>
      </div>
      
      <br>
      
        <%= form_tag endangered_destroy_path do %>
        <%= submit_tag "Delete Endangered Sharks" %>
        <% end %>
      
        <br>
      
      <%= link_to 'New Shark', new_shark_path, :class => "btn btn-primary btn-sm" %> <%= link_to 'Home', home_index_path, :class => "btn btn-primary btn-sm" %>
      

      This code includes the ICUN status codes once again, and a Bootstrap table for the outputted data. By looping through our @endangered variable, we output the name and ICUN status of each shark to the table.

      Below the table, we have another set of form_tags and submit_tags, which post to the destroy path by offering users the option to "Delete Endangered Sharks".

      Save and close the file when you are finished editing.

      The last modification we’ll make to our views will be in the index view associated with our home controller. You may recall that this view is set as the root of the application in config/routes.rb.

      Open this file for editing:

      • nano app/views/home/index.html.erb

      Find the column in the row that states Sharks are ancient:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . . 
              <div class="col-lg-6">
                  <h3>Sharks are ancient</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago.
                  </p>
              </div>
          </div>
      </div>
      

      Add the following code to the file:

      ~/rails-sidekiq/app/views/home/index.html.erb

      . . . 
              <div class="col-lg-6">
                  <h3>Sharks are ancient and SOME are in danger</h3>
                  <p>There is evidence to suggest that sharks lived up to 400 million years ago. Without our help, some could disappear soon.</p>
                  <p><%= button_to 'Which Sharks Are in Danger?', endangered_index_path, :method => :get,  :class => "btn btn-primary btn-sm"%>
                  </p>
              </div>
          </div>
      </div>
      

      We’ve included a call to action for users to learn more about endangered sharks, by first sharing a strong message, and then adding a button_to helper that submits a GET request to our endangered index route, giving users access to that part of the application. From there, they will be able to upload and view endangered shark information.

      Save and close the file when you are finished editing.

      With your code in place, you are ready to start the application and upload some sharks!

      Step 5 — Starting Sidekiq and Testing the Application

      Before we start the application, we’ll need to run migrations on our database and start Sidekiq to enable our workers. Redis should already be running on the server, but we can check to be sure. With all of these things in place, we’ll be ready to test the application.

      First, check that Redis is running:

      You should see output like the following:

      Output

      ● redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2019-11-12 20:37:13 UTC; 1 weeks 0 days ago

      Next, run your database migrations:

      You can now start Sidekiq in the context of your current project bundle by using the bundle exec sidekiq command:

      You will see output like this, indicating that Sidekiq is ready to process jobs:

      Output

      m, `$b .ss, $$: .,d$ `$$P,d$P' .,md$P"' ,$$$$$b/md$$$P^' .d$$$$$$/$$$P' $$^' `"/$$$' ____ _ _ _ _ $: ,$$: / ___|(_) __| | ___| | _(_) __ _ `b :$$ ___ | |/ _` |/ _ |/ / |/ _` | $$: ___) | | (_| | __/ <| | (_| | $$ |____/|_|__,_|___|_|__|__, | .d$$ |_| 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Running in ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux] 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: See LICENSE and the LGPL-3.0 for licensing details. 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org 2019-11-19T21:43:00.540Z pid=17621 tid=gpiqiesdl INFO: Booting Sidekiq 6.0.3 with redis options {:id=>"Sidekiq-server-PID-17621", :url=>nil} 2019-11-19T21:43:00.543Z pid=17621 tid=gpiqiesdl INFO: Starting processing, hit Ctrl-C to stop

      Open a second terminal window, navigate to the rails-sidekiq directory, and start your application server.

      If you are running the application locally, use the following command:

      If you are working with a development server, run the following:

      • bundle exec rails s --binding=your_server_ip

      Navigate to localhost:3000 or http://your_server_ip:3000 in the browser. You will see the following landing page:

      Sidekiq App Home

      Click on the Which Sharks Are in Danger? button. Since you have not uploaded any endangered sharks, this will take you to the endangered index view:

      Endangered Index View

      Click on Import Endangered Sharks to import the sharks. You will see a status message telling you that the sharks have been imported:

      Begin Import

      You will also see the beginning of the import. Refresh your page to see the entire table:

      Refresh Table

      Thanks to Sidekiq, our large batch upload of endangered sharks has succeeded without locking up the browser or interfering with other application functionality.

      Click on the Home button at the bottom of the page, which will bring you back to the application main page:

      Sidekiq App Home

      From here, click on Which Sharks Are in Danger? again. This will now take you directly to the data view, since you already uploaded the sharks.

      To test the delete functionality, click on the Delete Endangered Sharks button below the table. You should be redirected to the home application page once again. Clicking on Which Sharks Are in Danger? one last time will take you back to the index view, where you will have the option to upload sharks again:

      Endangered Index View

      Your application is now running with Sidekiq workers in place, which are ready to process jobs and ensure that users have a good experience working with your application.

      Conclusion

      You now have a working Rails application with Sidekiq enabled, which will allow you to offload costly operations to a job queue managed by Sidekiq and backed by Redis. This will allow you to improve your site’s speed and functionality as you develop.

      If you would like to learn more about Sidekiq, the docs are a good place to start.

      To learn more about Redis, check out our library of Redis resources. You can also learn more about running a managed Redis cluster on DigitalOcean by looking at the product documentation.



      Source link