sidekiq redis
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.
在开发Ruby on Rails应用程序时,您可能会发现应异步执行应用程序任务。 处理数据,发送批处理电子邮件或与外部API交互都是可以与后台作业异步完成的工作示例。 使用后台作业可以通过将可能耗时的任务卸载到后台处理队列中,从而释放原始的请求/响应周期,从而提高应用程序的性能。
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.
Sidekiq是可以在Rails应用程序中实现的,使用更广泛的后台作业框架之一。 它由Redis支持, Redis是一种内存中的键值存储,以其灵活性和性能而著称。 Sidekiq使用Redis作为作业管理存储,以每秒处理数千个作业 。
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:
在本教程中,您将Redis和Sidekiq添加到现有的Rails应用程序中。 您将创建一组Sidekiq工作者类和方法来处理:
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.
完成后,您将拥有一个演示应用程序,该应用程序使用工作程序和作业来异步处理任务。 使用本教程作为起点,这将为您在自己的应用程序中添加工作人员和工作提供良好的基础。
To follow this tutorial, you will need:
要遵循本教程,您将需要:
A local machine or development server running Ubuntu 18.04. Your development machine should have a non-root user with administrative privileges and a firewall configured with ufw
. For instructions on how to set this up, see our Initial Server Setup with Ubuntu 18.04 tutorial.
运行Ubuntu 18.04的本地计算机或开发服务器。 您的开发机器应具有具有管理特权的非root用户,以及使用ufw
配置的防火墙。 有关如何进行此设置的说明,请参阅我们的《 Ubuntu 18.04初始服务器设置》教程。
Node.js and npm installed on your local machine or development server. This tutorial uses Node.js version 10.17.0 and npm version 6.11.3. For guidance on installing Node.js and npm on Ubuntu 18.04, follow the instructions in the “Installing Using a PPA” section of How To Install Node.js on Ubuntu 18.04.
安装在本地计算机或开发服务器上的Node.js和npm 。 本教程使用Node.js 10.17.0版和npm 6.11.3版。 有关在Ubuntu 18.04上安装Node.js和npm的指导,请遵循如何在Ubuntu 18.04上安装Node.js的“使用PPA安装”部分中的说明。
The Yarn package manager installed on your local machine or development server. You can following the installation instructions in the official documentation.
安装在本地计算机或开发服务器上的Yarn程序包管理器 。 您可以按照官方文档中的安装说明进行操作 。
Ruby, rbenv, and Rails installed on your local machine or development server, following Steps 1-4 in How To Install Ruby on Rails with rbenv on Ubuntu 18.04. This tutorial uses Ruby 2.5.1, rbenv 1.1.2, and Rails 5.2.3.
遵循在Ubuntu 18.04上如何使用rbenv安装Ruby on Rails的 步骤1-4中的步骤 ,将Ruby, rbenv和Rails安装在本地计算机或开发服务器上 。 本教程使用Ruby 2.5.1 ,rbenv 1.1.2和Rails 5.2.3 。
SQLite installed, following Step 1 of How To Build a Ruby on Rails Application. This tutorial uses SQLite 3 3.22.0.
按照如何在Ruby on Rails应用程序中构建Ruby的 步骤1安装SQLite。 本教程使用SQLite 3 3.22.0 。
Redis installed, following Steps 1-3 of How To Install and Secure Redis on Ubuntu 18.04. This tutorial uses Redis 4.0.9.
按照如何在Ubuntu 18.04上安装和保护Redis的 步骤1-3的步骤 安装Redis 。 本教程使用Redis 4.0.9 。
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.
我们的第一步是从DigitalOcean社区GitHub帐户中克隆rails-bootstrap存储库。 该存储库包含来自如何将Bootstrap添加到Ruby on Rails应用程序中描述的设置代码,该代码说明了如何将Bootstrap添加到现有的Rails 5项目。
Clone the repository into a directory called rails-sidekiq
:
将存储rails-sidekiq
到名为rails-sidekiq
的目录中:
git clone https://github.com/do-community/rails-bootstrap.git rails-sidekiq
git clone https://github.com/do-community/rails-bootstrap.git rails-sidekiq
Navigate to the rails-sidekiq
directory:
导航到rails-sidekiq
目录:
cd rails-sidekiq
cd 导轨-sidekiq
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.
为了使用代码,您首先需要安装项目的依赖项,这些依赖项在其Gemfile中列出。 您还需要将sidekiq gem添加到项目中,才能与Sidekiq和Redis一起使用。
Open the project’s Gemfile for editing, using nano
or your favorite editor:
使用nano
或您喜欢的编辑器打开项目的Gemfile进行编辑:
Add the gem anywhere in the main project dependencies (above development dependencies):
在主要项目依赖项中(开发依赖项之上)的任意位置添加gem:
. . .
# 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:
使用以下命令安装gem:
You will see in the output that the redis
gem is also installed as a requirement for sidekiq
.
您将在输出中看到,也已安装redis
gem作为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.
接下来,您将安装Yarn依赖项。 由于该Rails 5项目已被修改为通过Webpack服务资产,因此其JavaScript依赖项现在由Yarn管理。 这意味着有必要安装并验证项目的package.json
文件中列出的依赖项。
Run yarn install
to install these dependencies:
运行yarn install
安装以下依赖项:
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
捆绑exec rails s --binding = your_server_ip
Navigate to localhost:3000
or http://your_server_ip:3000
. You will see the following landing page:
导航到localhost:3000
或http:// your_server_ip :3000
。 您将看到以下登录页面:
To create a new shark, click on the Get Shark Info button, which will take you to the sharks/index
route:
要创建新的鲨鱼,请单击“ 获取鲨鱼信息”按钮,这将带您进入sharks/index
路线:
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.
为了验证该应用程序是否正常运行,我们可以向其中添加一些演示信息。 单击“ 新鲨鱼” 。 由于项目的身份验证设置 ,系统将提示您输入用户名( sammy )和密码( shark )。
On the New Shark page, input “Great White” into the Name field and “Scary” into the Facts field:
在“ 新鲨鱼”页面上,在“ 名称”字段中输入“ Great White”,在“ 事实”字段中输入“ Scary”:
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
.
单击创建鲨鱼按钮以创建鲨鱼。 一旦看到鲨鱼已创建,就可以使用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.
现在,您已经为项目安装了必要的依赖关系并测试了其功能。 接下来,您可以对Rails应用程序进行一些更改,以使用濒临灭绝的鲨鱼资源。
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.
首先,让我们为濒临灭绝的鲨鱼创建一个Endangered
模型。 我们将在数据库表中包含一个有关鲨鱼名称的字符串字段,并为国际自然保护联盟(IUCN) 类别提供另一个字符串字段,以确定每个鲨鱼面临的风险程度。
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:
最终,我们的模型结构将与用于创建批量上传文件的CSV文件中的列匹配。 该文件位于db
目录中,您可以使用以下命令检查其内容:
The file contains a list of 73 endangered sharks and their IUCN statuses - vu for vulnerable, en for endangered, and cr for critically endangered.
该文件包含73种濒危鲨鱼及其IUCN状态的列表-vu表示脆弱, en表示濒危, cr表示严重濒危。
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:
我们的Endangered
模型将与此数据相关联,从而使我们能够从此CSV文件创建新的Endangered
实例。 使用以下命令创建模型:
Next, generate an Endangered
controller with an index
action:
接下来,生成带有index
操作的Endangered
控制器:
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.
尽管我们还需要向Rails为我们生成的控制器文件中添加自定义方法,但这将为我们构建应用程序功能提供一个起点。
Open that file now:
立即打开该文件:
Rails has provided us with a skeletal outline that we can begin to fill in.
Rails为我们提供了可以开始填写的骨架轮廓。
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.
首先,我们需要确定处理数据所需的路线。 多亏了generate controller
命令,我们才有了一个index
方法。 这将与index
视图相关联,在index
视图中,我们将为用户提供上载濒临灭绝的鲨鱼的选项。
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.
但是,我们还将要处理用户可能已经上传了鲨鱼的情况; 在这种情况下,他们将不需要上传选项。 我们将以某种方式需要评估已经存在多少个Endangered
类实例,因为不止一个实例表明已经进行了批量上传。
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:
首先创建一个set_endangered
private
方法,该方法将从数据库中获取Endangered
类的每个实例。 将以下代码添加到文件中:
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.
请注意, before_action
过滤器将确保仅为index
和data
路由设置@endangered
的值,这将是我们处理濒临灭绝的鲨鱼数据的位置。
Next, add the following code to the index
method to determine the correct path for users visiting this part of the application:
接下来,将以下代码添加到index
方法中,以确定访问该应用程序此部分的用户的正确路径:
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.
如果我们的Endangered
类的实例超过0个,我们将把用户重定向到data
路由,他们可以在其中查看有关所创建的鲨鱼的信息。 否则,他们将看到index
视图。
Next, below the index
method, add a data
method, which will correlate to a data
view:
接下来,在index
方法下面,添加一个data
方法,该方法将与data
视图相关:
. . .
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.
接下来,我们将添加一种方法来处理数据上传本身。 我们将这种方法称为upload
,它将调用Sidekiq worker类和方法以从CSV文件执行数据上传。 在下一步中,我们将为此工人类AddEndangeredWorker
创建定义。
For now, add the following code to the file to call the Sidekiq worker to perform the upload:
现在,将以下代码添加到文件中,以调用Sidekiq worker执行上传:
. . .
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.
通过使用CSV文件作为参数调用AddEndangeredWorker
类上的perform_async
方法,此代码可确保将鲨鱼数据和上载作业传递给Redis。 我们将设置的Sidekiq工作人员将监视作业队列,并在出现新作业时做出响应。
After calling perform_async
, our upload
method redirects to the data
path, where users will be able to see the uploaded sharks.
调用perform_async
,我们的upload
方法将重定向到data
路径,用户可以在其中看到上载的鲨鱼。
Next, we’ll add a destroy
method to destroy the data. Add the following code below the upload
method:
接下来,我们将添加一个destroy
方法来销毁数据。 在upload
方法下面添加以下代码:
. . .
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.
像我们的upload
方法一样, destroy
方法包括对RemoveEndangeredWorker
类(我们将创建的另一个Sidekiq工作者)的perform_async
调用。 调用此方法后,它将用户重定向到根应用程序路径。
The finished file will look like this:
完成的文件将如下所示:
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.
作为巩固应用程序路由的最后一步,我们将修改config/routes.rb
(路由声明所在的文件)中的代码。
Open that file now:
立即打开该文件:
The file currently looks like this:
该文件当前如下所示:
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.
我们将需要更新文件以包含我们在控制器中定义的路由: data
, upload
和destroy
。 我们的data
路由将与GET请求匹配以检索鲨鱼数据,而我们的upload
和destroy
路由将映射到上载和销毁该数据的POST请求。
Add the following code to the file to define these routes:
将以下代码添加到文件中以定义这些路由:
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.
有了Endangered
模型和控制器,您现在就可以继续定义Sidekiq工作者类。
We have called perform_async
methods on our Sidekiq workers in our controller, but we still need to create the workers themselves.
我们已经在控制器中的Sidekiq工作程序上调用了perform_async
方法,但是我们仍然需要自己创建工作程序。
First, create a workers
directory for the workers:
首先,为workers
创建一个workers
目录:
Open a file for the AddEndangeredWorker
worker:
打开AddEndangeredWorker
工作者的文件:
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:
在此文件中,我们将添加允许我们处理CSV文件中的数据的代码。 首先,将代码添加到将创建该类的文件中,包括Ruby CSV库 ,并确保该类充当Sidekiq Worker:
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.
我们还包括retry: false
选项,以确保Sidekiq在失败的情况下不重试上传。
Next, add the code for the perform
function:
接下来,添加perform
函数的代码:
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.
perform
方法从控制器中定义的perform_async
方法接收参数,因此对齐参数值很重要。 在这里,我们传入控制器中定义的变量csv_file
,并使用CSV库中的foreach
方法读取文件中的值。 设置headers: true
此循环为headers: true
可以确保将文件的第一行视为标题行。
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.
然后,该块将文件中的值读入我们为Endangered
模型设置的列中: name
和iucn
。 运行此循环将为CSV文件中的每个条目创建Endangered
实例。
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:
接下来,我们将创建一个工作程序来处理删除此数据。 打开RemoveEndangeredWorker
类的文件:
Add the code to define the class, and to ensure that it uses the CSV library and functions as a Sidekiq Worker:
添加代码以定义类,并确保其使用CSV库并充当Sidekiq Worker:
class RemoveEndangeredWorker
include Sidekiq::Worker
sidekiq_options retry: false
end
Next, add a perform
method to handle the destruction of the endangered shark data:
接下来,添加一个perform
方法来处理濒临灭绝的鲨鱼数据的破坏:
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.
perform
方法在Endangered
类上调用destroy_all
,这将从数据库中删除该类的所有实例。
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.
在工作人员就位后,您可以继续为endangered
视图创建布局,并为index
和data
视图创建模板,以便用户可以上载和查看濒临灭绝的鲨鱼。
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.
为了使用户能够欣赏到濒临灭绝的鲨鱼信息,我们需要解决两件事: endangered
控制器中定义的视图的布局以及index
和data
视图的视图模板。
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.
当前,我们的应用程序使用位于app/views/layouts/application.html.erb
的整个应用程序范围的布局,导航部分和sharks
视图的布局。 应用程序布局检查内容块,这使我们能够根据用户参与的应用程序部分来加载不同的布局:对于home
index
页面,他们将看到一个布局,以及与各个鲨鱼有关的任何视图,他们会看到另一个。
We can repurpose the sharks
layout for our endangered
views since this format will also work for presenting shark data in bulk.
我们可以将sharks
布局重新设置为endangered
视图,因为这种格式也可以用于批量显示鲨鱼数据。
Copy the sharks
layout file over to create an endangered
layout:
复制sharks
布局文件以创建endangered
布局:
Next, we’ll work on creating the view templates for our index
and data
views.
接下来,我们将为index
和data
视图创建视图模板。
Open the index
template first:
首先打开index
模板:
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:
删除样板代码并添加以下代码,这将为用户提供有关濒危类别的一些常规信息,并为他们提供上载有关濒危鲨鱼的信息的选项:
<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"
.
form_tag
通过将后操作指向endangered_upload_path
(我们为上载定义的路径)来使数据上载成为可能。 用submit_tag
创建的一个提交按钮,提示用户"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.
除了此代码外,我们还包含有关ICUN代码的一些常规信息,以便用户可以解释他们将看到的数据。
Save and close the file when you are finished editing.
完成编辑后,保存并关闭文件。
Next, open a file for the data
view:
接下来,打开data
视图文件:
Add the following code, which will add a table with the endangered shark data:
添加以下代码,这将添加一个包含濒临灭绝的鲨鱼数据的表:
<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.
该代码再次包含ICUN状态代码,以及用于输出数据的Bootstrap表。 通过遍历@endangered
变量,我们将每个鲨鱼的名称和ICUN状态输出到表中。
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"
.
在表格下面,我们还有另一组form_tags
和submit_tags
,它们通过为用户提供"Delete Endangered Sharks"
选项来发布到destroy
路径。
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
.
我们将对视图进行的最后修改将在与home
控制器关联的index
视图中。 您可能还记得,该视图在config/routes.rb
设置为应用程序的根目录。
Open this file for editing:
打开此文件进行编辑:
Find the column in the row that states Sharks are ancient
:
在指出Sharks are ancient
的行中找到一列:
. . .
<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:
将以下代码添加到文件中:
. . .
<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.
我们包含了一个号召性用语,要求用户首先共享一个强烈的信息,然后添加一个button_to
帮助程序,以向我们的endangered
index
路由提交GET请求,从而进一步了解濒临灭绝的鲨鱼,从而使用户可以访问应用程序的该部分。 从那里,他们将能够上载和查看濒临灭绝的鲨鱼信息。
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!
编写好代码后,就可以启动应用程序并上传一些鲨鱼了!
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.
在启动应用程序之前,我们需要在数据库上运行迁移并启动Sidekiq以启用我们的工作程序。 Redis应该已经在服务器上运行了,但是我们可以确定一下。 具备所有这些条件之后,我们将准备测试该应用程序。
First, check that Redis is running:
首先,检查Redis是否正在运行:
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:
现在,您可以使用bundle exec sidekiq
命令在当前项目包的上下文中启动Sidekiq:
You will see output like this, indicating that Sidekiq is ready to process jobs:
您将看到如下输出,表明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
Open a second terminal window, navigate to the rails-sidekiq
directory, and start your application server.
打开第二个终端窗口,导航到rails-sidekiq
目录,然后启动应用程序服务器。
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
捆绑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:
在浏览器中导航到localhost:3000
或http:// your_server_ip :3000
。 您将看到以下登录页面:
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
视图:
Click on Import Endangered Sharks to import the sharks. You will see a status message telling you that the sharks have been imported:
单击“ 导入濒临灭绝的鲨鱼”以导入鲨鱼。 您将看到一条状态消息,告诉您鲨鱼已被导入:
You will also see the beginning of the import. Refresh your page to see the entire table:
您还将看到导入的开始。 刷新页面以查看整个表格:
Thanks to Sidekiq, our large batch upload of endangered sharks has succeeded without locking up the browser or interfering with other application functionality.
感谢Sidekiq,我们成功上传了大批濒临灭绝的鲨鱼,而没有锁定浏览器或不干扰其他应用程序功能。
Click on the Home button at the bottom of the page, which will bring you back to the application main page:
单击页面底部的“ 主页”按钮,这将使您返回到应用程序主页:
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.
从这里,单击哪些鲨鱼处于危险之中? 再次。 因为您已经上传了鲨鱼,现在这将直接将您带到data
视图。
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:
要测试删除功能,请单击表下方的“ 删除濒临灭绝的鲨鱼”按钮。 您应该再次重定向到主应用程序页面。 单击哪些鲨鱼处于危险之中? 最后一次将带您回到index
视图,在该视图中,您可以选择再次上传鲨鱼:
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.
您的应用程序现在已经在运行Sidekiq的工作程序中运行,这些工作程序已准备就绪,可以处理作业,并确保用户在使用您的应用程序方面拥有良好的体验。
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.
现在,您具有启用了Sidekiq的工作Rails应用程序,它将使您可以将昂贵的操作卸载到由Sidekiq管理并由Redis支持的作业队列中。 这将使您在开发时提高站点的速度和功能。
If you would like to learn more about Sidekiq, the docs are a good place to start.
如果您想了解有关Sidekiq的更多信息,那么文档是一个不错的起点。
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.
要了解有关Redis的更多信息,请查看我们的Redis资源库。 您还可以通过查看产品文档来了解有关在DigitalOcean上运行托管Redis群集的更多信息。
sidekiq redis