python基础——redis操作

redis操作

先导入redis模块

import redis


def main():
    client = redis.Redis(host='127.0.0.1', port=6379, password='')
    print(client)
    client.set('username', 'hellokitty', ex=300)
    print(client.get('username'))


if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Redis 是一个非常流行的内存数据存储系统,它可以用于缓存、分布式锁、消息队列等场景。在 Python 中,我们通常使用 RedisPython 客户端库——redis-py 来操作 Redis。 下面是 Redis 工程化的 Python 写法: 1. 安装redis-py ```python pip install redis ``` 2. 连接 Redis ```python import redis # 创建连接池 pool = redis.ConnectionPool(host='localhost', port=6379, db=0) # 创建 Redis 客户端 r = redis.Redis(connection_pool=pool) # 测试连接是否成功 print(r.ping()) # 输出:True ``` 3. 设置键值对 ```python # 设置键值对 r.set('name', 'John') # 获取值 name = r.get('name') print(name.decode()) # 输出:John ``` 4. 设置过期时间 ```python # 设置键值对,并设置过期时间为 60 秒 r.setex('name', 60, 'John') # 获取值 name = r.get('name') print(name.decode()) # 输出:John # 等待 60 秒后获取值 time.sleep(60) name = r.get('name') print(name) # 输出:None ``` 5. 使用管道操作 ```python # 创建管道 pipe = r.pipeline() # 将多个命令放入管道中 pipe.set('name', 'John') pipe.set('age', 18) # 执行命令 pipe.execute() # 获取值 name = r.get('name') age = r.get('age') print(name.decode(), age.decode()) # 输出:John 18 ``` 6. 使用 Lua 脚本 ```python # 定义 Lua 脚本 script = """ local counter = redis.call("incr", KEYS[1]) if tonumber(counter) == 1 then redis.call("expire", KEYS[1], ARGV[1]) return 1 elseif tonumber(counter) > tonumber(ARGV[2]) then return 0 else return 1 end """ # 加载 Lua 脚本 script_sha = r.script_load(script) # 执行 Lua 脚本 result = r.evalsha(script_sha, 1, 'limit:127.0.0.1', 60, 10) print(result) # 输出:1 ``` 以上是 Redis 工程化的 Python 写法,可以更好地适应实际项目的需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值