私の問題を説明するために、単純な Cramp http://cramp.in/クラスを添付します。いくつかの変更を追加しますが、主にhttps://github.com/lifo/cramp-pub-sub-chat-demo/blob/master/app/actions/chat_action.rbのように機能します
class ChatAction < Cramp::Websocket
use_fiber_pool
on_start :create_redis
on_finish :handle_leave, :destroy_redis
on_data :received_data
def create_redis
@redis = EM::Hiredis.connect('redis://127.0.0.1:6379/0')
end
def destroy_redis
@redis.pubsub.close_connection
@redis.close_connection
end
def received_data(data)
msg = parse_json(data)
case msg[:action]
when 'join'
handle_join(msg)
when 'message'
handle_message(msg)
else
# skip
end
end
def handle_join(msg)
@user = msg[:user]
subscribe
publish(:action => 'control', :user => @user, :message => 'joined the chat room')
end
def handle_leave
publish :action => 'control', :user => @user, :message => 'left the chat room'
end
def handle_message(msg)
publish(msg.merge(:user => @user))
# added only for inline sync tests
render_json(:action => 'message', :user => @user, :message => "this info should appear after published message")
end
private
def subscribe
@redis.pubsub.subscribe('chat') do |message|
render(message)
end
end
def publish(message)
@redis.publish('chat', encode_json(message))
end
def encode_json(obj)
Yajl::Encoder.encode(obj)
end
def parse_json(str)
Yajl::Parser.parse(str, :symbolize_keys => true)
end
def render_json(hash)
render encode_json(hash)
end
end
私がやろうとしていることの詳細は、handle_message メソッドにあります。
クライアントに正しい順序でメッセージを送信しようとしました。最初にすべてのサブスクライバーにメッセージを発行し、次に現在接続されているクライアントに対してのみ内部情報をレンダリングします。
上記のコードの場合、クライアントは次を受け取ります。
{"action":"message","user":"user1","message":"this info should appear after published message"}
{"action":"message","message":"simple message","user":"user1"}
おそらく em-hiredis の遅延可能な応答のため、同期されていません。だから私はこの方法でそれを同期しようとします:
def handle_message(msg)
EM::Synchrony.sync publish(msg.merge(:user => @user))
EM::Synchrony.next_tick do # if I comment this block messages order is still incorrect
render_json(:action => 'message', :user => @user, :message => "this info should appear after published message")
end
end
現在、クライアントは正しい順序でメッセージを処理します。
{"action":"message","message":"simple message","user":"user1"}
{"action":"message","user":"user1","message":"this info should appear after published message"}
私の質問は次のとおりです。
- EM::Synchrony.next_tick ブロックにコメントすると、メッセージの順序が正しくありません。この例の EM::Synchrony.next_tick ブロックにはどのような意味がありますか?
- これは Cramp または EventMachine とのインライン同期を処理する良い方法ですか?
- それを処理するためのより良い、より明確な方法はありますか?
ありがとうございました!