1. 当前位置:网站首页 > Redis

Python操作redis方法


Python使用redis方法

  • [x] 安装了python
  • [x] 安装了redis
  • [x] 安装了redis包

    pip3 install redis -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

    # coding=utf-8
    import redis
    import time
    
    def main():
        redis_host = "127.0.0.1"
        redis_password = "test123456"
        redis_cli = redis.StrictRedis(host=redis_host, port=6379, db=0, password=redis_password)
        # noinspection PyBroadException
        try:
            print(redis_cli.flushdb()) # 清空数据库
            redis_cli.randomkey() # 随机获得一个key,如果数据库为空,返回nil
            redis_cli.set("key1", "hello")
            print(redis_cli.keys("key*")) # 获得当前数据库所有的“key*” 模糊匹配
            print(redis_cli.exists("key3")) # 查看key是否存在
            print(redis_cli.type("key2")) # 查看key对应的值类型
            redis_cli.move("key3", 1) # 移动对应key(key3)到对应数据库(1)
            redis_cli.select(1) #  切换到数据库(1)
            redis_cli.delete("key3") # 删除key
            print(redis_cli.get("key2")) # 获得key2数据
            redis_cli.rename("key2", "key3") # 将key2重命名key3
            redis_cli.rename("key1", "key3") # 尝试将key2重命名key3,若key3存在则失败
            redis_cli.expire("key1", 100) # 设置key1键时效100秒
            redis_cli.ttl("key1") # 查看key1时效
            redis_cli.expire("key1", 10) # 重置key1键时效10秒
            redis_cli.persist("key1") # 取消key1超时,设置为永久
            print(redis_cli.ttl("key1")) # 查看key1时效,持久键返回-1
        except Exception as e:
            print(e.message)
       finally:
           redis_cli.flushdb()
       pass
    
    if __name__ == "__main__":
        # 启动项目
        main()


本文最后更新于2021-3-21,已超过 3个月没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
版权说明

本文地址:http://www.liuyangdeboke.cn/?post=4
未标注转载均为本站远程,转载请注明文章出处:

发表评论

联系我们

在线咨询:点击这里给我发消息

微信号:17721538135

工作日:9:00-23:00,节假日休息

扫码关注