Python開源: 一個簡單小巧、可定制化、輕量級的基于內存的 Python 緩存組件

WhitneyDuhi 6年前發布 | 38K 次閱讀 Python Python開發

python-common-cache

該項目是一個基于內存的緩存組件,它是輕量級的、簡單的和可自定義化的,你可以以一種非常簡單的方法來實現你的需求。

Features

  • 開箱即用,沒有復雜的配置代碼,你可以通過默認配置來簡單、輕松地使用緩存,但同時也支持自定義配置以滿足需求,例如,自定義evict策略、清理策略以及是否使用線程池等等。
  • 細粒度的過期時間控制,每個緩存實例對象都含有一個全局的過期時間,但你也可以通過函數put(key, value, expire)來設置局部的過期時間。
  • 通過函數cache_loader(key)和cache_writer(key, value)以支持構建多級緩存系統,前者可以在緩存未命中的情況下從其他緩存系統或者數據源讀取緩存,后者則可以將查詢到的結果寫入到另一個緩存系統或者數據源,以上兩個函數都需要你自己實現并配置到緩存實例對象中。
  • 當緩存的容量已滿時,默認使用LRU(Least-Recently-Used)策略進行回收舊數據,并且還提供了另外兩種其他的策略:FIFO(First-In-First-Out)與LFU(Least-Frequently-Used)。
  • 通過函數replace_evict_func(func)與replace_cleanup_func()支持在運行時進行動態替換驅逐策略與清理策略。
  • 在緩存實例對象實例化時創建一個用于定期清理無效緩存項的守護進程,而且緩存實例對象在每次使用get()/put()/pop()操作之后,都會調用清理函數進行清理。
  • 每個緩存實例對象默認都有一個用于提高吞吐量的線程池,你可以在創建緩存實例時選擇不使用線程池,例如“cache = Cache(enable_thread_pool = False)”,也可以在運行時對線程池進行動態開關。
  • 記錄了每個緩存項的統計信息,包括命中次數、命中率、未命中次數、expire時間、剩余時間、創建時間和key與value,你可以通過調用statistic_record()函數來獲得這些信息。

Usage

首先你需要通過pip進行安裝。

pip install python-common-cache

有兩種使用方法, 第一種就是直接使用緩存實例,就像使用一個dict一樣:

cache = Cache(expire=10)
cache['key'] = 'data'
def foo():

# cache hit and return data from the cache
if cache['key'] is not None:
    return cache['key']
# cache miss and return data from a data source or service
....</code></pre> 

第二種是通過緩存實例提供的裝飾器,這種方法更加方便且實用:

>>> import time
>>> cache = Cache()
>>> @cache.access_cache(key='a')
... def a():
...     return 'a from data source'
>>> a()
'a from data source'
>>> cache.get('a')
'a from data source'
>>> cache.put(key='b', value='b from cache')
>>> @cache.access_cache(key='b')
... def b():
...     return 'b from data source'
>>> b()
'b from cache'
>>> c_key = 'c'
>>> @cache.access_cache(key_location_on_param=0)
... def c(key):
...     return 'c from data source'
>>> c(c_key)
'c from data source'
>>> cache.get(c_key)
'c from data source'
>>> @cache.access_cache(key='d', auto_update=False)
... def d():
...     return 'd from data source'
>>> d()
'd from data source'
>>> cache.get('d') == None
True
>>> @cache.access_cache(key='e', cache_loader=lambda k: '%s from cache loader' % k)
... def e():
...     return 'e from data source'
>>> e()
'e from cache loader'
>>> out_dict = {}
>>> def writer(k, v):
...     out_dict[k] = v
>>> @cache.access_cache(key='f', cache_writer=writer)
... def f():
...     return 'f from data source'
>>> f()
'f from data source'
>>> time.sleep(1) # wait to execute complete because it in the other thread
>>> out_dict
{'f': 'f from data source'}
>>> cache.with_cache_loader(lambda k: '%s from cache loader(global)' % k)
True
>>> @cache.access_cache(key='g')
... def g():
...     return 'g from data source'
>>> g()
'g from cache loader(global)'

更多的用法請閱讀Cache類的源碼,其中有非常多的使用案例代碼以供參考。

 

 本文由用戶 WhitneyDuhi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!