建立与Redis的连接
import redis
pool = redis.ConnectionPool(host='localhost', port=6379)
# 默认情况下每创建一个Redis实例都会构造出一个ConnectionPool实例,每一次访问redis都会从这个连接池得到一个连接,操作完成后会把该连接放回连接池(连接并没有释放),可以构造一个统一的ConnectionPool,在创建Redis实例时,可以将该ConnectionPool传入,那么后续的操作会从给定的ConnectionPool获得连接,不会再重复创建ConnectionPool。
# 默认情况下没有设置keepalive和timeout,建立的连接是blocking模式的短连接。
# 不考虑底层tcp的情况下,连接池中的连接会在ConnectionPool.disconnect中统一销毁。
r = redis.Redis(connection_pool=pool)
或
r = redis.StrictRedis(host='localhost', port=6379)
操作
方式一:根据数据类型的不同,调用相应的方法,完成读写
r.set('name','hello')
temp = r.get('name')
print(temp)
>> b'hello' # b代表二进制 .decode() 一下就好了
方式二:pipline
缓冲多条命令,然后一次性执行,减少服务器-客户端之间TCP数据库包,从而提高效率
pipe = r.pipeline()
pipe.set('name', 'world')
pipe.get('name')
pipe.execute() # 一次性执行缓存的命令
示例:用户登录
业务过程如下:
输入用户名、密码
密码加密
判断redis中是否记录了用户名,如果有则成功
如果redis中没有用户名,则到mysql中查询
从mysql中查询成功后,将用户名记录到redis中
import pymysql,redis
username = input("请输入用户名:")
password = input("请输入密码:")
pool = redis.ConnectionPool(host='localhost', port=6379)
r = redis.Redis(connection_pool=pool) # 创建redis连接
if r.get(username):
if password == r.get(username).decode(): # python3获取的是bytes类型,要decode一下
print('redis')
print("登录成功!")
else:
print("密码输入错误")
else:
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxx', db='xingedb') # 创建mysql连接
cursor = conn.cursor() # 创建游标
try:
cursor.execute('select password from cmdb_userinfo where username = %s;',[username,]) # 执行SQL语句,并返回受影响的行数
pwd = cursor.fetchone()[0]
if pwd == password:
print('mysql')
print('登录成功!')
r.set(username, password)
else:
print("密码输入错误")
except Exception as e:
print("您输入的用户不存在")
conn.commit() # 提交,不然无法保存新建或者修改的数据
cursor.close() # 关闭游标
conn.close() # 关闭连接