最近在项目中做了个直播 + 在线聊天的功能,然后老大希望直播时可以看到在线人数。
相关文章比较少,于是爬了两天坑,想了个比较简单的方案:
periodically :collect_online_users, every: 10.seconds
让channel
每 10 秒发布collect_online_users
的动作collect_online_users
发布的消息后通过 perform("save_user_id")
调用服务端save_user_id
方法,把id
存入缓存中periodically :boardcast_user_numbers, every: 1.minutes
每分钟发布在线用户数配置 redis 参考:使用 Redis 处理 Rails Model 缓存
服务端代码
# app/channels/live_channel.rb
class LiveChannel < ApplicationCable::Channel
periodically :boardcast_user_numbers, every: 1.minutes
periodically :collect_online_users, every: 10.seconds
after_subscribe :boardcast_user_numbers
def subscribed
stream_for live
end
def unsubscribed
end
def save_user_id
if $redis_user_attendances.get(live.id).nil?
$redis_user_attendances.set live.id, [current_user.id].to_json
else
users = JSON.parse($redis_user_attendances.get(live.id))
users.push(current_user.id)
$redis_user_attendances.set live.id, users.to_json
end
end
def collect_online_users
LiveChannel.broadcast_to live, type: "comfirm_online"
end
def boardcast_user_numbers
users = JSON.parse($redis_user_attendances.get(live.id))
count = users.uniq.length
$redis_user_attendances.set(live.id,"[]") //清空redis缓存
LiveChannel.broadcast_to live, {type: "update_online_user_number",data:count}
end
private
def live
Live.find(params[:id])
end
end
let vm = this
this.$cable.subscriptions.create({
channel: 'LiveChannel',
id: this.live.id
}, {
received: function ({type, data}) {
if (type == "update_online_user_number") {
vm.user_online_numbers = data //记录用户数
} else if (type == "comfirm_online"){
this.perform("save_user_id")
}
}
})
功能比较简单 就是记录在线人数而已 😂