环境
Windows11 + Python3.X + Pycharm社区版
思路
1 github下载redis压缩包 ,安装并启动redis服务,在Pycharm中运行python程序,连接redis服务,熟悉redis的使用和巩固python语言。
2 python开发环境的搭建参考 https://mp.csdn.net/mp_blog/creation/editor/144119111
步骤
1 下载Zip包
https://github.com/tporadowski/redis/releases

下载之后

2 解压zip包
解压之后,文件夹改名为Redis50:

Redis50目录下的文件:

3 启动redis服务
进入Redis50目录,用cmd命令启动服务
bash
redis-server.exe redis.windows.conf

可以把Redis50的路径加到系统的环境变量path里,直接用redis-server命令启动,省略后面的redis.windows.conf参数。


该窗口不要关闭,客户端要连接服务端。
4 启动redis客户端
新开一个cmd窗口,输入如下命令
bash
redis-server.exe redis.windows.conf

如果在环境变量path中添加了redis的安装目录,在任意命令行运行redis-cli都可以启动客户端

5 验证安装结果
用get/set命令验证,redis是否安装成功。
bash
set mykey abc
get mykey
6 pip安装redis包
pycharm中安装redis包
bash
pip install redis

7 python连接redis
7.1 常规连接
python
#!/usr/bin/python3
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('mykey', 'hello, redis')
value = r.get('mykey')
print(value)

redis 取出的结果默认是字节,设定 decode_responses=True 改成字符串(hello,redis前面少量了字母b)

db0是默认的数据库,没有指定具体使用哪个数据库时,Redis会自动选择db0作为当前使用的数据库。
7.2 使用连接池
默认,每个Redis实例都会维护一个自己的连接池。可以建立一个连接池,多个 Redis 实例共享一个连接池。
python
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('mykey', 'hello, redis poll')
value = r.get('mykey')
print(value)
r.close()
