Replacing an item in memcached without changing the expiration date

I have several memcached elements that expire 24 hours after creation. I need to update these items while keeping the validity period intact.

How can i do this? Apparently, the expiration parameter is required for the replacement function.

+3
source share
2 answers

If you need this type of expiration control, you will need to bear the expiration time of the stored item along with the item itself.

, . , memcached, . , , , .

[ entry, expiresAt ]

TTL raw memcached , LRU.

memcached , .

+3

, , . Python:

class ExpiringCache(BaseCache):
    """A cache that allows you to update values without changing when the
    data will expire. We do this by storing when the value was
    inserted in the cache and decrementing the timeout when we update.

    """
    def get(self, key, *args, **kwargs):
        raw_value = super(ExpiringCache, self).get(key, *args, **kwargs)

        # we get None on a cache miss, but otherwise it a 3-tuple
        if raw_value is None:
            return None

        value, start_time, timeout = raw_value
        return value

    def set(self, key, value, *args, **kwargs):
        timeout = kwargs.get('timeout')

        raw_value = (value, now(), timeout)
        super(ExpiringCache, self).set(key, raw_value, *args, **kwargs)

    def update(self, key, value, timeout=None):
        """If this value is still in the cache, update it but reduce the
        timeout. If it not present, just set it.

        """
        raw_value = super(ExpiringCache, self).get(key)

        if raw_value is None:
            self.set(key, value, timeout=timeout)
            return

        original_value, start_time, original_timeout = raw_value

        if not original_timeout:
            # we are caching without a timeout, so just set the new value
            self.set(key, value, timeout=original_timeout)
            return

        elapsed_time = (now() - start_time).total_seconds()
        remaining_timeout = timeout - elapsed_time

        if remaining_timeout > 0:
            self.set(key, value, timeout=remaining_timeout)
0

Source: https://habr.com/ru/post/1717851/


All Articles