Rails开发后台调用API功能-faraday+sidekiq

流程设计

  • 前端点击按钮‘开始同步’ 异步执行,remote: true
  • controller运行rsync,调用后台任务
  • controller通过channel发出通知‘正在同步...请不要关闭页面’给前端
  • job处理完成,通过channel发送通知给前端‘同步完成。刷新本页面’
  • 完成

基础工作

#Gemfile
gem ‘faraday’
gem 'sidekiq'
$ rails g controller V1::AdminPanel::Workers sync

增加前端按钮

= link_to t('v1.page.admin_panel.actions.sync'), path, remote: true, method: :post, data: { confirm: t('v1.page.admin_panel.管理员列表.同步吗')}, class: 'ui right floated small negative button'

控制器返回信息

def sync
  render js: "$('.ui.modal').modal('show');"
  MesSyncJob.perform_later(I18n.locale.to_s)
  #传客户的语言给activejob
end

在资源下增加Route

reources :workers do
  collection do
    post :sync
  end
end

channels

class MesJobChannel < ApplicationCable::Channel
  CHANNEL_NAME = 'MES_JOB_CHANNEL'
  def subscribed
     ....
  end
end

ActiveJob

#sync_job.rb
class SyncJob < ApplicationJob
  def perform()
    ...
 ActionCable.server.broadcast(MesJobChannel::CHANNEL_NAME, {info: info, title: title})
  end
end

Cable.yml

development:
  adapter: redis
  url: redis://localhost:6379/1
...

你可能感兴趣的:(Rails开发后台调用API功能-faraday+sidekiq)