• python-redis


    1、使用python的redis模块进行连接

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    import redis
    redisDB = redis.Redis(host='127.0.0.1',port=6379,db=0)
    keys = redisDB.keys()#获取所有的键
    print keys

    2、使用redis的连接池连接

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    import redis
    redisPool = redis.ConnectionPool(host='127.0.0.1',port=6379)
    redisDB = redis.Redis(connection_pool=redisPool)
    keys = redisDB.keys()#获取所有的keys
    print keys

    3、管道(redis每次执行完毕就会断开连接,使用管道可以一次执行多个指令)

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    import redis
    redisPool = redis.ConnectionPool(host='127.0.0.1',port=6379)
    redisDB = redis.Redis(connection_pool=redisPool)
    pipe = redisDB.pipeline(transaction=True)
    redisDB.set('name','zs')
    redisDB.set('sex','male')
    pipe.execute()

    4、发布和订阅

    1、定义帮助类
    #
    !/usr/bin/env python # _*_ coding:utf-8 _*_ import redis class redisHelper: #定义类,类中定义发布和订阅方法 def __init__(self,channel=None): self.conn = redis.Redis(host='127.0.0.1',port=6379) self.channel = channel def publish(self,msg): #定义发布方法 if self.channel and msg: self.conn.publish(self.channel,msg) return True else: return False def subscribe(self): #定义订阅方法 pub = self.conn.pubsub() if self.channel: pub.subscribe(self.channel) return pub else: return False
    2、先订阅频道
    #
    !/usr/bin/env python # _*_ coding:utf-8 _*_ from demo.redis_study.redishelp import redisHelper # 订阅 redis_obj = redisHelper('mychannle') sub_obj = redis_obj.subscribe() while True: msg = sub_obj.parse_response() #获取发布的结果 print msg
    3、在指定频道发布信息
    #
    !/usr/bin/env python # _*_ coding:utf-8 _*_ from demo.redis_study.redishelp import redisHelper # 发布 redis_obj = redisHelper('mychannle') redis_obj.publish('hello')

  • 相关阅读:
    div标签和span标签的简单区别
    方法重载的好处及区别
    异步计算工具
    设置"用于统计的冗余字段"要谨慎
    如何建立索引
    NFS,Memcached,Tokyo tyrant实现session共享性能测试
    mysql cache功能小记
    PHP程序员也要学会使用“异常”
    xdebug: var_dump函数设置
    用shell写个简单的log监控程序
  • 原文地址:https://www.cnblogs.com/aadmina/p/9334069.html
Copyright © 2020-2023  润新知