Class: Tina4::RedisBackplane

Inherits:
WebSocketBackplane show all
Defined in:
lib/tina4/websocket_backplane.rb

Overview

Redis pub/sub backplane.

Requires the redis gem (+gem install redis+). The require is deferred so the rest of Tina4 works fine without it installed — an error is raised only when this class is actually instantiated.

Instance Method Summary collapse

Methods inherited from WebSocketBackplane

create_backplane

Constructor Details

#initialize(url: nil) ⇒ RedisBackplane

Returns a new instance of RedisBackplane.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/tina4/websocket_backplane.rb', line 74

def initialize(url: nil)
  begin
    require "redis"
  rescue LoadError
    raise LoadError,
      "The 'redis' gem is required for RedisBackplane. " \
      "Install it with: gem install redis"
  end

  @url = url || ENV.fetch("TINA4_WS_BACKPLANE_URL", "redis://localhost:6379")
  @redis = Redis.new(url: @url)
  @subscriber = Redis.new(url: @url)
  @threads = {}
  @running = true
end

Instance Method Details

#closeObject



110
111
112
113
114
115
116
# File 'lib/tina4/websocket_backplane.rb', line 110

def close
  @running = false
  @threads.each_value { |t| t.kill }
  @threads.clear
  @subscriber.close
  @redis.close
end

#publish(channel, message) ⇒ Object



90
91
92
# File 'lib/tina4/websocket_backplane.rb', line 90

def publish(channel, message)
  @redis.publish(channel, message)
end

#subscribe(channel, &block) ⇒ Object



94
95
96
97
98
99
100
101
102
# File 'lib/tina4/websocket_backplane.rb', line 94

def subscribe(channel, &block)
  @threads[channel] = Thread.new do
    @subscriber.subscribe(channel) do |on|
      on.message do |_chan, msg|
        block.call(msg) if @running
      end
    end
  end
end

#unsubscribe(channel) ⇒ Object



104
105
106
107
108
# File 'lib/tina4/websocket_backplane.rb', line 104

def unsubscribe(channel)
  @subscriber.unsubscribe(channel)
  thread = @threads.delete(channel)
  thread&.join(1)
end