zoukankan      html  css  js  c++  java
  • redis(六)

    安装包

    sudo pip install redis
    
    • 使用源码安装
    unzip redis-py-master.zip
    cd redis-py-master
    sudo python setup.py install
    

    交互代码

    • 引入模块
    import redis
    
    • 连接
    try:
        r=redis.StrictRedis(host='localhost',port=6379)
    except Exception,e:
        print e.message
    • 方式一:根据数据类型的不同,调用相应的方法,完成读写

    更多方法同前面学的命令

    r.set('name','hello')
    r.get('name')
    • 方式二:pipline
    • 缓冲多条命令,然后一次性执行,减少服务器-客户端之间TCP数据库包,从而提高效率
      pipe = r.pipeline()
      pipe.set('name', 'world')
      pipe.get('name')
      pipe.execute()

    封装

    • 连接redis服务器部分是一致的
    • 这里将string类型的读写进行封装
      import redis
      class RedisHelper():
          def __init__(self,host='localhost',port=6379):
              self.__redis = redis.StrictRedis(host, port)
          def get(self,key):
              if self.__redis.exists(key):
                  return self.__redis.get(key)
              else:
                  return ""
          def set(self,key,value):
              self.__redis.set(key,value)

    示例:用户登录

    • 业务过程如下:
    • 输入用户名、密码
    • 密码加密
    • 判断redis中是否记录了用户名,如果有则成功
    • 如果redis中没有用户名,则到mysql中查询
    • 从mysql中查询成功后,将用户名记录到redis中
    #encoding=utf-8
    from t2 import RedisHelper
    from t3 import MysqlHelper
    import hashlib
    
    name=raw_input("请输入用户名:")
    pwd=raw_input("请输入密码:")
    
    sha1=hashlib.sha1()
    sha1.update(pwd)
    pwd1=sha1.hexdigest()
    
    try:
        redis=RedisHelper()
        if redis.get('uname')==name:
            print 'ok'
        else:
            mysql=MysqlHelper('localhost',3306,'test1','root','mysql')
            upwd=mysql.get_one('select upwd from userinfos where uname=%s',[name])
            if upwd==None:
                print '用户名错误'
            elif upwd[0]==pwd1:
                redis.set('uname', name)
                print '登录成功'
            else:
                print "密码错误"
    except Exception,e:
        print e.message
  • 相关阅读:
    google protobuf
    spawn-fcgi和libfcgi源码解读
    [Linux] 查看进程的上下文切换pidstat
    [MySQL] update语句的redo log过程
    [转载] PHP 8新特性之JIT简介
    [PHP] 新浪企邮webmail在memcache实践使用共享session
    [Go] Golang练习项目-web客服系统即时通讯websocket项目go-fly
    [PHP] php8的jit不支持32位系统WARNING: JIT not supported by host architecture
    [PHP] 源码编译安装opcache
    [PHP] 查找使用的哪个配置文件php.ini
  • 原文地址:https://www.cnblogs.com/leecoffee/p/9039239.html
Copyright © 2011-2022 走看看