mirror of
https://github.com/discourse/discourse.git
synced 2024-12-24 04:54:54 +08:00
3c44bed545
Its implementation was already distributed-mutex-like, with slight differences that did not seem necessary.
32 lines
718 B
Ruby
32 lines
718 B
Ruby
# frozen_string_literal: true
|
|
|
|
class DistributedMemoizer
|
|
# never wait for longer that 1 second for a cross process lock
|
|
MAX_WAIT = 1
|
|
|
|
# memoize a key across processes and machines
|
|
def self.memoize(key, duration = 60 * 60 * 24, redis = Discourse.redis)
|
|
redis_lock_key = self.redis_lock_key(key)
|
|
redis_key = self.redis_key(key)
|
|
|
|
DistributedMutex.synchronize(redis_lock_key, redis: redis, validity: MAX_WAIT) do
|
|
result = redis.get(redis_key)
|
|
|
|
unless result
|
|
result = yield
|
|
redis.setex(redis_key, duration, result)
|
|
end
|
|
|
|
result
|
|
end
|
|
end
|
|
|
|
def self.redis_lock_key(key)
|
|
"memoize_lock_#{key}"
|
|
end
|
|
|
|
def self.redis_key(key)
|
|
"memoize_#{key}"
|
|
end
|
|
end
|