gpt4 book ai didi

redis - Rails 5 API + 实时通知

转载 作者:IT王子 更新时间:2023-10-29 05:59:19 26 4
gpt4 key购买 nike

我只创建了一个 Rails 5 API,我需要创建一个实时网络通知。

使用 ActionCable 有可能吗?有没有人有 Action Cable 或任何其他解决方案的示例?

提前致谢。

最佳答案

这是一个网络通知 channel ,允许您在向正确的流广播时触发客户端网络通知:

创建服务器端网络通知 channel :

# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end

创建客户端网络通知 channel 订阅:

# app/assets/javascripts/cable/subscriptions/web_notifications.coffee
# Client-side which assumes you've already requested
# the right to send web notifications.
App.cable.subscriptions.create "WebNotificationsChannel",
received: (data) ->
new Notification data["title"], body: data["body"]

从您应用程序的其他地方向网络通知 channel 实例广播内容:

# Somewhere in your app this is called, perhaps from a NewCommentJob
WebNotificationsChannel.broadcast_to(
current_user,
title: 'New things!',
body: 'All the news fit to print'
)

WebNotificationsChannel.broadcast_to 调用在当前订阅适配器的 pubsub 队列中为每个用户放置一条单独的广播名称下的消息。对于 ID 为 1 的用户,广播名称将为 web_notifications:1

关于redis - Rails 5 API + 实时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40272066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com