-->

Ruby on Rails PubNub subscribe as separate process

2019-05-21 06:17发布

问题:

I was consider using PubNub on my website.

In turn, I can subscribe to channels with PubNub.

However, I need to find a way to run a script that subscribes to channels with PubNub.

For example, according to their documentation http://www.pubnub.com/blog/ruby-push-api , it states "To listen for published messages, call the subscribe function. It is important to note: the subscribe function is blocking. You will want to run this function in a separate process."

Then PubNub provides the following code:

 ## Subscribe (Listen for Messages)
 pubnub.subscribe({
'channel ' => 'my_channel',
'callback' => lambda do |message|
    ## Message Received!!!
    puts(message['my_var']) ## print message
    return true             ## keep listening?
end
  })

I cannot think of a way to run this function as a "process."

Isn't there something like background jobs? Is this what I would need?

Appreciate any guidance.

回答1:

The best way to get started with this (at this time) is to use the Ruby EventMachine async HTTP request method and the PubNub HTTP REST API.

  1. EventMachine::Protocols::HttpClient2 -> http://eventmachine.rubyforge.org/EventMachine/Protocols/HttpClient2.html
  2. PubNub HTTP REST API -> http://www.pubnub.com/tutorial/http-rest-push-api

    conn = EM::Protocols::HttpClient2.connect 'pubsub.pubnub.com', 80
    req  = conn.get('/subscribe/SUBSCRIBE_KEY/CHANNEL/0/TIMETOKEN')
    

Note that this is not a full example, but a good starting point... You must follow the HTTP REST Guide.