Python-连接Redis并操作

首先开启redis的外连

sch01ar@ubuntu:~$ sudo vim /etc/redis/redis.conf

 把bind 127.0.0.1这行注释掉

Python-连接Redis并操作

然后重启redis

sudo /etc/init.d/redis-server restart

这样ubuntu的redis本机就可以连接了

连接并操作

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import redis

r = redis.Redis(host='192.168.220.144', port=6379)
r.set('name', 'John')
print(r.get('name'))

运行结果

Python-连接Redis并操作

ubuntu上redis的结果

Python-连接Redis并操作

连接池

python操作redis,操作一次就请求一次连接,操作完成就断开连接,连接池把redis的连接请求放入池中,方便操作,避免每次建立、释放连接的开销

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import redis

pool = redis.ConnectionPool(host='192.168.220.144', port=6379)
r = redis.Redis(connection_pool=pool)

r.set('age', 22)
print(r.get('age'))

运行结果

Python-连接Redis并操作

ubuntu上redis的结果

Python-连接Redis并操作

管道

在一次请求中执行多条命令,可以使用管道实现在一次请求中执行多条命令

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import redis

pool = redis.ConnectionPool(host='192.168.220.144', port=6379, db=2)
r = redis.Redis(connection_pool=pool)

pipe = r.pipeline(transaction=True)

pipe.set('name', 'John')
pipe.set('age', 22)

pipe.execute()

运行结果

Python-连接Redis并操作