zoukankan      html  css  js  c++  java
  • python(十)Redis操作

    1.需要先导入Redis模块

    import redis

    2. 连接redis

    r=redis.Redis(host='XXXXXXXXXX',password='XXXXX',db=XX,decode_responses=True)#这里的decode_responses是说等到的结果是字符不是bytes类型

    3. 操作redis

    redis有多种数据类型,主要说string类型和hash类型

    1.string类型:#存数据是k-v类型

    a. 增加数据:r.set('小明','11')

        修改数据:r.set('小明','12')

        获取数据:r.get('小明')

        删除数据:r.delete('小明')

    设置失效时间:(‘小明','12222',30)

    #字符串类型,形式是k-v
    r.set("lcl_session","xxxxxxx",5)#新增数据,5代表失效时间,默认是永久
    session = r.get("lcl_session")#获取key的值
    print(session)
    new_session = session.decode()#如果连接时没有设置decode_responses=True,需要手动将获取的值转换为字符串
    print(new_session)
    # print(r.set("lcl_session","11111111"))
    print(r.get("lcl_session"))
    r.delete()#删除

    2.hash类型:#存的数据是大key-小key-value

    a. 增加数据:r.hset('xiaoming','shhd','5')

        修改数据:r.hset('xiaoming','shhd','5')

         获取数据:r.hget('xiaoming','shhd')#获取指定小key的value

                           r.hset('xiaoming')#获取大key里的所有key和value

           删除数据:r.hdel('xiaoming','shhd')#删除小key里的值

                              r.hset('xiaoming')#删除大key里的所有的key和value

    r.hset("ssy_student","wanghe","xxx")
    
    r.hset("ssy_student","lj","xxx11")
    r.hset("ssy_student","cmc","xxx1122")
    r.hset("ssy_student","ccx","xxx11223")
    # print(r.hget("ssy_student","cmc").decode())
    print(r.hget("ssy_student","cmc"))
    print(r.get("lj_session"))
    r.hdel("ssy_student","ccx")
    print(r.hgetall("ssy_student"))
    
    print(r.keys()) #所有的key
    print(r.keys('*session*'))#模糊匹配
    print(r.exists("lcl_session"))#key是否存在
    print(r.type("lj_session"))
    print(r.type("ssy_student"))
    r.expire("ssy_student",50)#指定某个key的过期时间

    3. r.flushdb()#清除redis中的所有key

    r.flushdb()#清除所有数据库里面所有的key

    r.key()#获取当前数据库里面所有的key,也有过滤功能

    r.expire() #设置失效时间

  • 相关阅读:
    How to change hostname on SLE
    How to install starDIct on suse OS?
    python logging usage
    How to reset password for unknow root
    How to use wget ?
    How to only capute sub-matched character by grep
    How to inspect who is caller of func and who is the class of instance
    How to use groovy script on jenkins
    Vim ide for shell development
    linux高性能服务器编程 (二) --IP协议详解
  • 原文地址:https://www.cnblogs.com/dmjsd/p/11166263.html
Copyright © 2011-2022 走看看