You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.1 KiB
42 lines
1.1 KiB
module UserOnline
|
|
class << self
|
|
def login(user_id)
|
|
set_bit(user_id, 1)
|
|
end
|
|
|
|
def logout(user_id)
|
|
set_bit(user_id, 0)
|
|
end
|
|
|
|
def set_bit(user_id, flag)
|
|
if !Rails.cache.data.exists(cache_key)
|
|
Rails.cache.data.setbit(cache_key, user_id, flag)
|
|
Rails.cache.data.expire(cache_key, 2 * 60 + 10)
|
|
else
|
|
Rails.cache.data.setbit(cache_key, user_id, flag)
|
|
end
|
|
end
|
|
|
|
def count
|
|
if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore)
|
|
Rails.cache.data.bitcount(cache_key)
|
|
else
|
|
0
|
|
end
|
|
end
|
|
|
|
def cache_key
|
|
if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore)
|
|
# 如设置2分钟内即120秒有请求的用户视为在线, 则最大会统计到4分钟内有活动用户
|
|
# TODO 更精确时长
|
|
begin_hour = Time.now.beginning_of_hour
|
|
minutes_piece = (Time.now - begin_hour) / 120
|
|
time = begin_hour.since((minutes_piece.to_i - 1) * 120).strftime("%H-%M")
|
|
"online_user_#{time}"
|
|
else
|
|
raise '请配置config.cache_store = redis_store'
|
|
end
|
|
end
|
|
end
|
|
end
|