zoukankan      html  css  js  c++  java
  • 使用Python操作memcache

    Python连接memcached的库有很多,处于简单以及高效的原则,最终选择了pymemcache,

    1. 优点
      1. 完全实现了memcached text协议
      2. 对于send/recv操作可以配置timeout
      3. 支持"noreply"特性,该可行可以先出的提高写的速度
      4. 使序列化/反序列化更简单
      5. 可以将网络异常,memecached错误当成是缓存丢失
    2. 安装pymemcache
      pip install pymemcache
    3. 使用pymemcache
      1. 基本操作
        
        
        from pymemcache.client.base import Client
        
        client = Client(('localhost', 11211))
        client.set('some_key', 'some_value')
        result = client.get('some_key')
      2. 使用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')
      3. 序列化操作
        
        
        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')
    4. 最佳实践
      1. 在构造Client时,添加timeout 的配置,防止block操作
      2. 使用“noreply”来提高性能,默认情况下改属性在“set”, “add”, “replace”, “append”, “prepend”, and “delete”.操作时是开启的,“cas”, “incr” and “decr”.操作时关闭的
      3. 尽可能的使用get_many以及gets_many操作,来减少round trip的操作实践
      4. 使用“ignore_exc” 属性,将网络异常,memecached错误当成是缓存丢失
  • 相关阅读:
    [转载] 十问 TiDB :关于架构设计的一些思考 TiDB
    blender low poly + unity 3d游戏制作
    d2js + activiti 备忘
    使用ActionFilterAttribute进行重定向注意事项
    一键发布部署vs插件[AntDeploy],让net开发者更幸福
    Docker常用命令
    C# 自然周,月,季度计算。
    .Net Core Web Api使用模型验证验证参数合法性
    WebApi 路由机制剖析
    WebApi路由机制详解
  • 原文地址:https://www.cnblogs.com/navysummer/p/9675952.html
Copyright © 2011-2022 走看看