Memcached使用總結之:使用Python操作memcache__Python

來源:互聯網
上載者:User
Python串連memcached的庫有很多,處於簡單以及高效的原則,最終選擇了pymemcache, 優點 完全實現了memcached text協議 對於send/recv操作可以配置timeout 支援"noreply"特性,該可行可以先出的提高寫的速度 使序列化/還原序列化更簡單 可以將網路異常,memecached錯誤當成是緩衝丟失 安裝pymemcache
pip install pymemcache 使用pymemcache 基本操作

from pymemcache.client.base import Clientclient = Client(('localhost', 11211))client.set('some_key', 'some_value')result = client.get('some_key')
使用memcache叢集
使用一致性HASH演算法支援叢集

from pymemcache.client.hash import HashClientclient = HashClient([('127.0.0.1', 11211),('127.0.0.1', 11212)])client.set('some_key', 'some value')result = client.get('some_key')

序列化操作

import jsonfrom pymemcache.client.base import Clientdef json_serializer(key, value):if type(value)== str:return value, 1     return json.dumps(value), 2def json_deserializer(key, value, flags):if flags == 1:return value    if flags == 2:return json.loads(value)raiseException("Unknown serialization format")client = Client(('localhost', 11211), serializer=json_serializer,                deserializer=json_deserializer)client.set('key',{'a':'b', 'c':'d'})result = client.get('key')

最佳實務 在構造Client時,添加timeout 的配置,防止block操作 使用“noreply”來提高效能,預設情況下改屬性在“set”, “add”, “replace”, “append”, “prepend”, and “delete”.操作時是開啟的,“cas”, “incr” and “decr”.操作時關閉的 儘可能的使用get_many以及gets_many操作,來減少round trip的操作實踐 使用“ignore_exc” 屬性,將網路異常,memecached錯誤當成是緩衝丟失 主要URL: pypi:https://pypi.python.org/pypi/ pymemcache 官方文檔: https://pymemcache.readthedocs.io/en/latest/getting_started.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.