一、Python库安装
1、联网安装
yum install epel-release -y
yum install python2-pip -y
pip install redis
2、使用源码安装
到中文官网查找客户端代码:
unzip redis-py-master.zip
cd redis-py-master
python setup.py install
3、检查python的redis扩展
python
import redis
二、Python与Redis交换
1、Python操作Redis单例
import redis
# 1.连接 Redis 服务器
try:
r=redis.StrictRedis(host='localhost', port=6379)
//r = redis.Redis(host='localhost', port=6379, password='', db=0)
except Exception as e:
print(e.message)
# 2.读写数据
# 方式一:根据数据类型的不同,调用相应的方法,完成读写
r.set('name','hello') # 设置 string 数据
r.get('name') # 读取 string 数据
# 方式二:使用 pipline
# 缓冲多条命令,然后一次性执行,减少数据传输频率,从而提高效率
pipe = r.pipeline()
pipe.set('name', 'world')
pipe.get('name')
pipe.execute()
2、Python操作Redis集群
python安装扩展用来操作redis集群:
pip install redis-py-cluster
操作集群的代码:
# -*- coding: utf-8 -*-
from rediscluster import StrictRedisCluster
redis_nodes = [{'host':'10.5.96.3','port':7000},
{'host':'10.5.96.3','port':7001},
{'host':'10.5.96.3','port':7002},
{'host':'10.5.96.3','port':8000},
{'host':'10.5.96.3','port':8001},
{'host':'10.5.96.3','port':8002}
]
redisconn = StrictRedisCluster(startup_nodes=redis_nodes)
redisconn.set('name100','shijiange')
print(redisconn.get('name100'))
三、数据操作
1、字符串相关操作
import redis
class TestString(object):
def __init__(self):
self.r = redis.StrictRedis(host='192.168.75.130',port=6379)
设置值
def test_set(self):
res = self.r.set('user1','juran-1')
print(res)
取值
def test_get(self):
res = self.r.get('user1')
print(res)
设置多个值
def test_mset(self):
d = {
'user2':'juran-2',
'user3':'juran-3'
}
res = self.r.mset(d)
取多个值
def test_mget(self):
l = ['user2','user3']
res = self.r.mget(l)
print(res)
删除
def test_del(self):
self.r.delete('user2')
2、列表相关操作
class TestList(object):
def __init__(self):
self.r = redis.StrictRedis(host='192.168.75.130',port=6379)
插入记录
def test_push(self):
res = self.r.lpush('common','1')
res = self.r.rpush('common','2')
# res = self.r.rpush('jr','123')
弹出记录
def test_pop(self):
res = self.r.lpop('common')
res = self.r.rpop('common')
范围取值
def test_range(self):
res = self.r.lrange('common',0,-1)
print(res)
3、集合相关操作
class TestSet(object):
def __init__(self):
self.r = redis.StrictRedis(host='192.168.75.130', port=6379)
添加数据
def test_sadd(self):
res = self.r.sadd('set01','1','2')
lis = ['Cat','Dog']
res = self.r.sadd('set02',lis)
删除数据
def test_del(self):
res = self.r.srem('set01',1)
随机删除数据
def test_pop(self):
res = self.r.spop('set02')
4、哈希相关操作
class TestHash(object):
def __init__(self):
self.r = redis.StrictRedis(host='192.168.75.130', port=6379)
批量设值
def test_hset(self):
dic = {
'id':1,
'name':'huawei'
}
res = self.r.hmset('mobile',dic)
批量取值
def test_hgetall(self):
res = self.r.hgetall('mobile')
判断是否存在 存在返回1 不存在返回0
def test_hexists(self):
res = self.r.hexists('mobile','id')
print(res)
四、Redis 操作封装
连接 Redis 服务器部分是一致的,以String类型的读写进行封装为例:
import redis
# Redis 工具类
class RedisTool():
# 初始化连接 Redis
def __init__(self, host='localhost', port=6379):
self.__redis = redis.StrictRedis(host, port)
# 读取 String 值
def get(self, key):
if self.__redis.exists(key): # 如果键存在
return self.__redis.get(key)
else: # 否则返回空值
return ""
# 设置 String 键值
def set(self, key, value):
self.__redis.set(key, value)
用户登录业务过程如下:
-
输入用户名、密码
-
密码加密
-
判断 Redis 中是否记录了用户名,如果有则成功
-
如果 Redis 中没有用户名,则到 Mysql 中查询
-
从 Mysql 中查询成功后,将用户名记录到 Redis 中
from t2 import RedisTool
from t3 import MysqlTool
import hashlib
name=input("请输入用户名:")
pwd=input("请输入密码:")
# 密码加密
sha1=hashlib.sha1()
sha1.update(pwd)
pwd1=sha1.hexdigest()
# 判断 Redis 中是否存在该用户信息的缓存数据
try:
redis=RedisTool()
if redis.get('uname') == name:
print('ok')
# 不存缓存,则走数据库进行用户信息校验
else:
mysql = MysqlTool('localhost', 3306, 'test1', 'root', 'mysql')
upwd = mysql.get_one('select upwd from userinfos where uname=%s', [name])
if upwd == None:
print('用户名错误')
elif upwd[0] == pwd1:
redis.set('uname', name) # 用户信息校验通过,则写入缓存
print('登录成功')
else:
print("密码错误")
except Exception as e:
print(e.message)