具有生存时间的 Python 内存缓存 [英] Python in-memory cache with time to live

查看:26
本文介绍了具有生存时间的 Python 内存缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个线程在运行相同的进程,它们需要能够相互通知在接下来的 n 秒内不应处理某些事情,但如果它们这样做了,那也不是世界末日.

I have multiple threads running the same process that need to be able to to notify each other that something should not be worked on for the next n seconds its not the end of the world if they do however.

我的目标是能够将字符串和 TTL 传递给缓存,并能够将缓存中的所有字符串作为列表获取.缓存可以存在于内存中,TTL 不会超过 20 秒.

My aim is to be able to pass a string and a TTL to the cache and be able to fetch all the strings that are in the cache as a list. The cache can live in memory and the TTL's will be no more than 20 seconds.

有人对如何实现这一点有任何建议吗?

Does anyone have a any suggestions for how this can be accomplished?

推荐答案

您可以使用 expiringdict 模块:

You can use the expiringdict module:

库的核心是 ExpiringDict 类,它是一个有序字典,具有用于缓存目的的自动过期值.

The core of the library is ExpiringDict class which is an ordered dictionary with auto-expiring values for caching purposes.

在描述中他们没有谈论多线程,所以为了不搞砸,使用Lock.

In the description they do not talk about multithreading, so in order not to mess up, use a Lock.

这篇关于具有生存时间的 Python 内存缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆