问题描述
我有以下使用 Eventmachine、Faye Websockets 和 RestClient 的代码:
class FxApi
def self.rates(base_currency = 'USD')
JSON.parse Restclient.get(FX_API_URL + '/latest',{ base: base_currency })
end
end
class ReportingApi
def self.add_quote(payload)
RestClient.post(REPORTING_API_URL + '/quote',payload)
end
end
rates = {}
EM.run do
# Keep updating currency rates every 10 seconds
EM.add_periodic_timer(10) do
rates = FxApi.latest
end
ws = Faye::WebSocket::Client.new('wss://ws.stock.com')
ws.on :open do |event|
ws.send({ event: 'subscribe',subscription: { name: 'quotes' } }.to_json)
end
ws.on :message do |event|
data = JSON.parse(event.data)
ReportingApi.add_quote(data)
if data['event'] == 'quote'
price_in_usd = data['price'] / rates[data['currency']]
if price_in_usd < 100
ws.send({ event: 'addOrder',params: { side: 'buy',qty: 1,type: 'market' } }.to_json)
end
end
end
end
我想确保 EM 中的所有“慢”任务(即 Web 请求)都是非阻塞的,这样它们就不会减慢整个 EM 循环的速度。
- Faye
ws.send
是否阻塞?如果是,如何使其非阻塞? - 如何使
FxApi.latest
无阻塞?你可以只做Thread.new { rates = FxApi.latest }
还是更复杂? - 还有什么需要考虑的吗?
我对 Eventmachine 还是比较陌生,老实说有点困惑 Ruby 的标准线程、EM 方式(EM.next_tick
、EM.defer
等)、RestClient adaptors 和 EM 定制的 HTTP客户端解决方案(例如 https://github.com/igrigorik/em-http-request)都相互关联。
是否有任何生产质量的开源项目或综合指南有助于了解常见模式?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)