今日内容概要
- python连接redis
- redis字符串操作
- redis之hash操作
- redis之列表操作
- redis其他 通用操作,管道
- django中使用redis
内容详细
1、python连接redis
pip install redis
没有,django中一个请求就会创建一个mysql连接,django并发量不高,mysql能撑住
想在django中使用连接池,有第三方:
https://www.cnblogs.com/wangruixing/p/13030755.html
http://liuqingzheng.top/python/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E9%AB%98%E9%98%B6/19-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E9%AB%98%E7%BA%A7%E5%AE%9E%E6%88%98%E4%B9%8B%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/
from redis import Redis
conn = Redis(host="localhost", port=6379, db=0, password=None)
conn.set('name', "lqz")
res = conn.get('name')
print(res)
创建文件redis_pool.py:
import redis
POOL = redis.ConnectionPool(max_connections=10, host="localhost", port=6379)
--------------------------------------------------------------------------------------------------------------
import redis
from redis_pool import POOL
conn = redis.Redis(connection_pool=POOL)
print(conn.get('name'))
from threading import Thread
import redis
import time
from redis_pool import POOL
def get_name():
conn = redis.Redis(connection_pool=POOL)
print(conn.get('name'))
for i in range(10):
t = Thread(target=get_name)
t.start()
time.sleep(2)
'''
1 咱们这个py作为脚本运行,不能使用相对导入
2 只能使用绝对导入
3 从环境变量中开始到导起
4 在pycharm中右键运行的脚本所在的目录,就会被加入到环境变量
'''
2、redis字符串操作
'''
1 set(name, value, ex=None, px=None, nx=False, xx=False)
ex,过期时间(秒)
px,过期时间(毫秒)
nx,如果设置为True,则只有name不存在时,当前set操作才执行,值存在,就修改不了,执行没效果
xx,如果设置为True,则只有name存在时,当前set操作才执行,值存在才能修改,值不存在,不会设置新值
2 setnx(name, value)
2 setex(name, value, time)
3 psetex(name, time_ms, value)
4 mset(*args, **kwargs)
5 get(name)
5 mget(keys, *args)
6 getset(name, value)
7 getrange(key, start, end)
8 setrange(name, offset, value)
9 setbit(name, offset, value)
10 getbit(name, offset)
11 bitcount(key, start=None, end=None)
12 bitop(operation, dest, *keys)
13 strlen(name)
14 incr(self, name, amount=1)
15 incrbyfloat(self, name, amount=1.0)
16 decr(self, name, amount=1)
17 append(key, value)
'''
import redis
conn = redis.Redis()
conn.set('age', 19)
"""
ex,过期时间(秒)---->过期时间
conn.set('age', 19, ex=3)
px,过期时间(毫秒) ---->过期时间
nx,如果设置为True,则只有name不存在时,当前set操作才执行, 值存在,就修改不了,执行没效果
conn.set('wife','dlrb',nx=True)
xx,如果设置为True,则只有name存在时,当前set操作才执行,值存在才能修改,值不存在,不会设置新值
conn.set('wife','dlrb',xx=True)
"""
print(conn.get('age1'))
print(conn.mget(['age1', 'age']))
print(conn.mget('name', 'age', 'age1'))
print(conn.getset('name', 'dsb'))
print(conn.getrange('name', 0, 1))
conn.setrange('name', 1, 'qqq')
conn.setbit('name', 1, 0)
print(conn.getbit('name', 1))
print(conn.bitcount('name', 0, 1))
print(conn.strlen('name'))
conn.incr('age')
conn.decr('age')
conn.append('name', 'nb')
3、redis之hash操作
'''
1 hset(name, key, value)
2 hmset(name, mapping)
3 hget(name,key)
4 hmget(name, keys, *args)
5 hgetall(name)
6 hlen(name)
7 hkeys(name)
8 hvals(name)
9 hexists(name, key)
10 hdel(name,*keys)
11 hincrby(name, key, amount=1)
12 hincrbyfloat(name, key, amount=1.0)
13 hscan(name, cursor=0, match=None, count=None)
14 hscan_iter(name, match=None, count=None)
'''
import redis
conn = redis.Redis()
conn.hset("userinfo", 'name', '彭于晏')
conn.hset("userinfo_01", mapping={'name': "刘亦菲", 'age': 18})
print(str(conn.hget('userinfo_01', 'name'), encoding='utf-8'))
print(str(conn.hget('userinfo_01', 'age'), encoding='utf-8'))
print(conn.hmget('userinfo_01', ['name', 'age']))
print(conn.hmget('userinfo_01', 'name', 'age'))
print(conn.hgetall('userinfo_01'))
print(conn.hlen('userinfo_01'))
print(conn.hkeys('userinfo_01'))
print(conn.hvals('userinfo_01'))
print(conn.hexists('userinfo_01', 'name'))
print(conn.hexists('userinfo_01', 'height'))
conn.hdel('userinfo_01', 'name')
conn.hincrby('userinfo_01', 'age')
res = conn.hscan('hash_test', 0, count=20)
print(res)
res = conn.hscan('hash_test', 352, count=20)
print(res)
print(len(res[1]))
res = conn.hscan_iter('hash_test', count=10)
for item in res:
print(item)

4、redis之列表操作
'''
1 lpush(name,values)
2 lpushx(name,value)
3 llen(name)
4 linsert(name, where, refvalue, value))
4 r.lset(name, index, value)
5 r.lrem(name, value, num)
6 lpop(name)
7 lindex(name, index)
8 lrange(name, start, end)
9 ltrim(name, start, end)
10 rpoplpush(src, dst)
11 blpop(keys, timeout)
12 brpoplpush(src, dst, timeout=0)
'''
import redis
conn = redis.Redis()
conn.lpush('girls', 'lyf', 'dlrb')
conn.rpush('girls', '杨颖')
conn.lpushx('girls', '杨颖1')
conn.lpushx('girl', '杨颖1')
print(conn.llen('girls'))
conn.linsert('girls', 'before', 'lyf', '张杰')
conn.linsert('girls', 'after', 'lyf', 'lqz')
conn.lset('girls', 1, 'lqz')
conn.lrem('girls', 1, 'lqz')
conn.lrem('girls', -1, 'lqz')
conn.lrem('girls', 0, 'lqz')
res = conn.lpop('girls')
print(res)
r = b'\xe6\x9d\xa8\xe9\xa2\x961'
print(str(r, encoding='utf-8'))
print(conn.lindex('girls', 1))
print(conn.lrange('girls', 0, 1))
conn.ltrim('girls', 1, 2)
print(conn.blpop('girls', timeout=1))
print(conn.brpoplpush('girls', 1)) 从指定索引阻塞式弹出
5、redis其他 通用操作及管道
5.1 其他操作
'''
delete(*names)
exists(name)
keys(pattern='*')
expire(name ,time)
rename(src, dst)
move(name, db))
randomkey()
type(name)
'''
import redis
conn = redis.Redis()
conn.delete('name','name1','hash1')
print(conn.delete('name'))
print(conn.delete('age'))
print(conn.keys())
print(conn.keys('us*'))
print(conn.keys('age?'))
conn.expire('age', 3)
conn.rename('wife', 'girl')
conn.move('girl', 3)
print(conn.randomkey())
print(conn.type('age1'))
print(conn.type('userinfo'))
5.2 管道
redis本身是不支持事务的
有的时候我们要实现类似这种功能:张三-100块钱,李四+100块钱
通过管道实现--->把多次操作的命令放到一个管道中,一次性执行,要么都执行了,要么都不执行
import redis
pool = redis.ConnectionPool()
conn = redis.Redis(connection_pool=pool)
pipe = conn.pipeline(transaction=True)
pipe.multi()
pipe.set('name', 'lqz')
pipe.set('role', 'nb')
pipe.execute()
6、django中使用redis
使用连接池 创建 pool.py:
import redis
POOL = redis.ConnectionPool(max_connections=10, host="localhost", port=6379)
任意位置使用
class TestView(APIView):
def get(self, requeste):
conn=redis.Redis(connection_pool=POOL)
print(conn.get('name'))
return Response('ok')
安装:pip install django-redis
在项目配置文件中:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
}
}
}
使用位置:
from django_redis import get_redis_connection
conn=get_redis_connection()
print(conn.get('name'))
cache.set('asdfasd','asdfas')
cache.set('wife',['dlrb','lyf'])
通过二进制可以在反序列化成功pyhton中的任意对象
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)