世界上最伟大的投资就是投资自己的教育
ruby 实现 RedisHashStore
随风 · 练气发布于1073 次点击
module RedisHashStore
extend self
class Entry
attr_reader :value
def initialize(value, expires_in:)
@value = value
@created_at = Time.now.to_f
@expires_in = expires_in
end
def expired?
@expires_in && @created_at + @expires_in <= Time.now.to_f
end
end
def write(hash_key, sub_key, value, **options)
entry = Entry.new(value, expires_in: options[:expires_in])
redis.hset(hash_key, sub_key, serialize_value(entry))
entry.value
end
def read(hash_key, sub_key)
entry = deserialize_value(redis.hget(hash_key, sub_key))
return if entry.blank?
if entry.expired?
delete(hash_key, sub_key)
return nil
end
entry.value
end
def delete(hash_key, sub_key)
redis.hdel(hash_key, sub_key)
end
def delete_hash(hash_key)
redis.del(hash_key)
end
private
def serialize_value(value)
Marshal.dump(value)
end
def deserialize_value(value)
return if value.nil?
Marshal.load(value)
end
def redis
Rails.cache.redis
end
end
0 条回复
暂无回复~~
© 汕尾市求知科技有限公司 | Rails365 Gitlab | 知乎 | b 站 | csdn
粤公网安备 44152102000088号 | 粤ICP备19038915号
Top