ruby 如何检查turbo rails中是否有广播订阅?

mwyxok5s  于 2023-04-29  发布在  Ruby
关注(0)|答案(2)|浏览(100)

在我的Rails视图中,我使用turbo_stream_from订阅turbo流广播来显示患者列表:

<%= turbo_stream_from :all_patients %>

我希望在创建新患者时更新此列表,因此我调用:

constly_method
Turbo::StreamsChannel.broadcast_update_to(:all_patients,...)

但是,我只想在当前有任何客户机实际订阅了:all_patients的情况下运行这段代码,因为这段代码需要占用一些计算资源。所以我想要的是

if Turbo::StreamsChannel.broadcast_subscribed?(:all_patients)
  constly_method
  Turbo::StreamsChannel.broadcast_update_to(:all_patients,...)
end

有什么办法可以查到吗?

ivqmmu1c

ivqmmu1c1#

ActionCanble数据可以通过查询访问。例如

ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect

文件:https://api.rubyonrails.org/v7.0/classes/ActionCable/RemoteConnections.html
它很好地发挥周围的查询来解决问题。(如果你能找到正确的答案。留言给我评论。我会用它来丰富我的文章)。希望这对你有帮助

iyzzxitl

iyzzxitl2#

<%= turbo_stream_from "channel_name" %> # on one page
<%= turbo_stream_from User.first %>     # on another page
  • Redis* 跟踪了其中的一些:
>> redis = Redis.new

# active channels
>> channels = redis.pubsub("channels") 
=> ["Z2lkOi8vc3RhY2tvdmVyZmxvdy9Vc2VyLzE", "_action_cable_internal", "channel_name"]

# subscribers, which are ActionCable servers
>> redis.pubsub("numsub", channels)
=> ["Z2lkOi8vc3RhY2tvdmVyZmxvdy9Vc2VyLzE", 1, "_action_cable_internal", 1, "channel_name", 1]

实际连接的用户数量,我认为不重要:

>> redis.pubsub("numsub", channels)
=> ["Z2lkOi8vc3RhY2tvdmVyZmxvdy9Vc2VyLzE", 0, "_action_cable_internal", 1, "channel_name", 1]
#                                          ^
# if i close user page, ActionCable disconnects from that channel

>> redis.pubsub("channels") 
=> ["_action_cable_internal", "channel_name"]

https://redis.io/commands/pubsub-channels/
这一个只适用于每个服务器示例,并为您提供每个通道连接的流的数量:

ActionCable.server.connections.flat_map do |conn|
  conn.subscriptions.send(:subscriptions).values
end.flat_map do |channel|
  # also streams seem to get stuck when code reloads in development
  # count goes up with every code change. must be a bug.
  channel.send(:streams).keys
end.tally
# => {"channel_name"=>4, "Z2lkOi8vc3RhY2tvdmVyZmxvdy9Vc2VyLzE"=>1}

相关问题