ChrisPalmer
ChrisPalmer

Reputation: 295

Getting Action Cable to broadcast in Sidekiq Job

I'm using Rails 5 in a docker environment and I can get Action Cable to broadcast on a Sidekiq worker perfectly fine, using worker.new.perform.

But for the life of me, I cannot get it to broadcast while using worker.perform_async.

Here is my cable.yml:

default: &default
 adapter: redis
 url: <%= ENV['REDIS_PROVIDER'] %>

development:
 <<: *default

test:
  <<: *default

production:
  <<: *default

Here is my worker:

class AdminWorker
  include Sidekiq::Worker

  def perform
    ActionCable.server.broadcast 'admin_channel', content: 'hello'
  end
 end

My Admin Channel:

class AdminChannel < ApplicationCable::Channel
 def subscribed
  stream_from "admin_channel"
 end

 def unsubscribed
  # Any cleanup needed when channel is unsubscribed
 end
end

As I mentioned earlier, this works just fine when calling AdminWorker.new.perform. As soon as I try to run AdminWorker.perform_async, the cable will not broadcast and nothing helpful regarding action cable in the logs. What am I missing here?

Upvotes: 18

Views: 8272

Answers (3)

Taimoor Changaiz
Taimoor Changaiz

Reputation: 10684

In development environment By default, ActionCable would run only on the rails server only. And it would not work in Sidekiq, console, cron jobs, etc. Because in config/cable.yml development server adapter is set to async

Solution: For ActionCable inter-process broadcasting, you have to set the adapter to Redis

In config/cable.yml

development:
 adapter: redis
 url: redis://localhost:6379/1
 channel_prefix: project_name_development

Upvotes: 0

srghma
srghma

Reputation: 5323

For those who wants to dockerize rails and sidekiq, you should run action_cable server separately like

puma -p 28080 cable/config.ru

https://nickjanetakis.com/blog/dockerize-a-rails-5-postgres-redis-sidekiq-action-cable-app-with-docker-compose

https://github.com/kchrismucheke/dockersample/blob/da5923899fb17682fabed041bef5381ed3fd91ab/config/application.rb#L57-L62

Upvotes: 1

Navin Gupta
Navin Gupta

Reputation: 364

I had the same problem. Came across this answer: ActionCable.server.broadcast from the console - worked for me. Basically just changed cable.yml

development:
  adapter: async

to

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

and I was able to broadcast from console, models, Sidekiq worker classes, etc.

Upvotes: 32

Related Questions