zoukankan      html  css  js  c++  java
  • Memcached使用总结之:使用Python操作memcache

    Python连接memcached的库有很多,处于简单以及高效的原则,最终选择了pymemcache,
    优点
    完全实现了memcached text协议
    对于send/recv操作可以配置timeout
    支持"noreply"特性,该可行可以先出的提高写的速度
    使序列化/反序列化更简单
    可以将网络异常,memecached错误当成是缓存丢失
    安装pymemcache
    pip install pymemcache
    使用pymemcache
    基本操作
    from pymemcache.client.base import Client

    client = Client(('localhost', 11211))
    client.set('some_key', 'some_value')
    result = client.get('some_key')
    使用memcache集群
    使用一致性HASH算法支持集群
    from pymemcache.client.hash import HashClient

    client = HashClient([('127.0.0.1', 11211),('127.0.0.1', 11212)])
    client.set('some_key', 'some value')
    result = client.get('some_key')

    序列化操作
    import json
    from pymemcache.client.base import Client

    def json_serializer(key, value):if type(value)== str:return value, 1
    return json.dumps(value), 2

    def 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
    ---------------------
    作者:Eric_aihua
    来源:CSDN
    原文:https://blog.csdn.net/eric_sunah/article/details/51612192?utm_source=copy
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    1442. Count Triplets That Can Form Two Arrays of Equal XOR
    1441. Build an Array With Stack Operations
    312. Burst Balloons
    367. Valid Perfect Square
    307. Range Sum Query
    1232. Check If It Is a Straight Line
    993. Cousins in Binary Tree
    1436. Destination City
    476. Number Complement
    383. Ransom Note
  • 原文地址:https://www.cnblogs.com/ExMan/p/9777900.html
Copyright © 2011-2022 走看看