【发布时间】:2020-09-05 19:40:01
【问题描述】:
我正在尝试使用 haproxy 来平衡我的 websocket 机架应用程序。
我使用 redis-cli 在频道 rates 中发布消息,这成功了 puts "sent" if ws.send(msg)
客户端确实收到了'Welcome! from server' 消息,所以我知道初始握手已完成。
但是,客户端永远不会收到频道“rates”中发布的消息。
web_socket.rb
require 'faye/websocket'
module WebSocket
class App
KEEPALIVE_TIME = 15 # in seconds
def initialize(app)
@app = app
@mutex = Mutex.new
@clients = []
# @redis = Redis.new(host: 'rds', port: 6739)
Thread.new do
@redis_sub = Redis.new(host: 'rds', port: 6379)
@redis_sub.subscribe('rates') do |on|
on.message do |channel, msg|
p [msg,@clients.length]
@mutex.synchronize do
@clients.each do |ws|
# ws.ping 'Mic check, one, two' do
p ws
puts "sent" if ws.send(msg)
# end
end
end
end
end
end
end
def call(env)
if Faye::WebSocket.websocket?(env)
# WebSockets logic goes here
ws = Faye::WebSocket.new(env, nil) # {ping: KEEPALIVE_TIME }
ws.on :open do |event|
p [:open, ENV['APPID'], ws.object_id]
ws.ping 'Mic check, one, two' do
# fires when pong is received
puts "Welcome sent" if ws.send('Welcome! from server')
@mutex.synchronize do
@clients << ws
end
p [@clients.length, ' Client Connected']
end
end
ws.on :close do |event|
p [:close, ENV['APPID'], ws.object_id, event.code, event.reason]
@mutex.synchronize do
@clients.delete(ws)
end
p @clients.length
ws = nil
end
ws.on :message do |event|
p [:message, event.data]
# @clients.each {|client| client.send(event.data) }
end
# Return async Rack response
ws.rack_response
else
@app.call(env)
end
end
end
end
我的 haproxy.cfg
frontend http
bind *:8080
mode http
timeout client 1000s
use_backend all
backend all
mode http
timeout server 1000s
timeout tunnel 1000s
timeout connect 1000s
server s1 app1:8080
server s2 app2:8080
server s3 app3:8080
server s4 app4:8080
请帮帮我!!!
编辑: 我试过Thread running in Middleware is using old version of parent's instance variable,但这不起作用。
如前所述。下面的代码成功
puts "sent" if ws.send(msg)
【问题讨论】:
标签: ruby websocket haproxy faye