redis介绍与安装
-数据库就是个存数据的地方:只是不同数据库数据组织,存放形式不一样
-mysql 关系型数据库(oracle,sqlserver,postgrasql)
-非关系型数据(no sql):redis,mongodb,clickhouse,infludb,elasticsearch,hadoop。。。
-没有sql:没有sql语句
-not olny sql 不仅仅是sql
-redis:一款纯内存存储的非关系型数据库(数据都在内存),速度非常快
-redis是一个key-value存储系统
-数据类型丰富,支持5大数据类型:字符串,列表,hash(字典),集合,有序集合
-纯内存操作
-可以持久化:能都把内存数据,保存到硬盘上永久存储
-1 纯内存,减少io
-2 使用了 io多路复用的 epoll 网络模型
-3 数据操作是单线程,避免了线程间切换
-多个客户端同时操作,不会存在并发安全问题
-redis:最新是7, 公司里5,6比较多
-redis:开源软件,免费的,他们不支持win
-epoll模型不支持win
-微软官方:基于源码修改---》编译成可执行文件
-第三方:https://github.com/tporadowski/redis/releases/
-win:下载安装包,一路下一步
-安装目录在环境变量中:任意路径敲 redis-server reidis-cli 都能找到
-把redis做成了服务,以后通过服务启动即可
-mac:官网下载,解压即可
-win,mac:两个可执行文件:
redis-server :等同于 mysqld
reidis-cli :等同于mysql
-使用服务启动
redis-server redis.windows-service.conf
-使用命令启动
redis-server
redis-cli
redis-cli -h 地址 -p 端口(默认端口6379)
-resp:后来收费了
-连接上发现有16个库
使用resp放入值
cmd中 连接:get key
Redis普通连接和连接池
在python中使用Redis
pip install redis
普通连接
from redis import Redis
def index():
coon = Redis(host="127.0.0.1", port=6379, db=0, decode_responses=True)
coon.set("name", "迪丽热巴")
res = coon.get("name")
print(res)
coon.close()
if __name__ == '__main__':
index()
连接池
设置连接池:
import redis
POOL = redis.ConnectionPool(host="127.0.0.1", port=6379, db=0, max_connections=5)
import redis
from pool import POOL
from threading import Thread
def index():
coon = redis.Redis(connection_pool=POOL)
print(coon.get("name"))
coon.close()
if __name__ == '__main__':
for i in range(10):
t = Thread(target=index)
t.start()
index()
python中实现单例的5种方式:
-1、使用模块级别的变量:Python的模块在程序中只会被导入一次,因此可以将需要实现单例的类定义为模块级别的变量。这样,每次导入该模块时都会使用同一个实例
class SingletonClass:
pass
singleton_instance = SingletonClass()
from singleton import singleton_instance
instance1 = singleton_instance
instance2 = singleton_instance
print(instance1 is instance2)
-2、使用装饰器:可以使用装饰器将类包装成单例。装饰器可以在每次创建实例时检查是否已经存在实例。
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class SingletonClass:
pass
instance1 = SingletonClass()
instance2 = SingletonClass()
print(instance1 is instance2)
-3、使用元类:元类是用于创建类的类。可以定义一个元类,在创建类时检查是否已经存在实例。
class SingletonMeta(type):
instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls.instances:
cls.instances[cls] = super().__call__(*args, **kwargs)
return cls.instances[cls]
class SingletonClass(metaclass=SingletonMeta):
pass
instance1 = SingletonClass()
instance2 = SingletonClass()
print(instance1 is instance2)
-4、使用基类:可以定义一个基类,将需要实现单例的类继承自该基类。基类在创建实例时会检查是否已经存在实例。
class SingletonBase:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = cls()
return cls._instance
class SingletonClass(SingletonBase):
pass
instance1 = SingletonClass.instance()
instance2 = SingletonClass.instance()
print(instance1 is instance2)
-5、使用线程安全的单例:如果需要在多线程环境下使用单例,可以使用线程安全的方式实现。可以使用线程锁来确保只有一个线程可以创建实例。
import threading
class SingletonClass:
_instance = None
_lock = threading.Lock()
@classmethod
def instance(cls):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = cls()
return cls._instance
instance1 = SingletonClass.instance()
instance2 = SingletonClass.instance()
print(instance1 is instance2)
Redis字符串类型
'''
1 set(name, value, ex=None, px=None, nx=False, xx=False)
2 setnx(name, value)
3 setex(name, value, time)
4 psetex(name, time_ms, value)
5 mset(*args, **kwargs)
6 get(name)
7 mget(keys, *args)
8 getset(name, value)
9 getrange(key, start, end)
10 setrange(name, offset, value)
11 setbit(name, offset, value)
12 getbit(name, offset)
13 bitcount(key, start=None, end=None)
14 bitop(operation, dest, *keys)
15 strlen(name)
16 incr(self, name, amount=1)
# incrby
17 incrbyfloat(self, name, amount=1.0)
18 decr(self, name, amount=1)
19 append(key, value)
'''
import redis
from pool import POOL
set:
coon = redis.Redis(connection_pool=POOL)
coon.set("name", "彭于晏")
coon.set("age", "18", ex=5)
coon.set("hobby", "篮球", px=5000)
coon.set("name", "yfh", nx=True)
coon.set("name", "yfh", xx=True)
ex、px、nx、xx的简写
coon.setnx("name", "彭于晏")
coon.setex("age", 5, "18")
coon.psetex("hobby", 5000, "篮球")
coon.mset({"name": "迪丽热巴", "age": 19, "hobby": "唱歌"})
get:
print(coon.get("name"))
print(coon.mget(["name", "sge", "hobby"]))
print(coon.mget(("name", "sge", "hobby")))
print(coon.getset("gender", "男"))
print(coon.getrange("name", 1, 3))
print(coon.setrange("name", 0, "oooo"))
操作比特位:
其他了解:
print(coon.strlen("name"))
coon.incr("age", 100)
coon.incrbyfloat('age', 1.1)
coon.decr("sge", 2)
coon.append("name", "pppppp")
coon.close()
常用:
'''
set、get、getrange、strlen
'''
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)
'''
内部的生成器:
def hscan_iter(self,name,match= None,count= None):
cursor = "0"
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor, match=match, count=count)
yield from data.items()
''' hash 类型,就是咱们python中的字典类型, 数据结构:数据的组织形式,底层存储 数组--->根据key值使用hash函数得到结构,存到数组中
字典的key值必须可hash
字典的key值必须是不可变数据类型
hash 类型无序,跟放的先后顺序无关的
python 的字典是 有序的 字典+列表
'''
import redis
conn = redis.Redis(decode_responses=True)
conn.hset("userinfo", "name", "qqq")
conn.hset("userinfo", "age", "18")
print(conn.hget("userinfo", "name"))
print(conn.hget("userinfo", "age"))
conn.hmget("userinfo", ["name", "age"])
print(conn.hgetall("userinfo"))
print(conn.hlen("userinfo"))
print(conn.hkeys("userinfo"))
print(conn.hvals("userinfo"))
print(conn.hexists("userinfo", "hobby"))
conn.hdel('userinfo', ['name', 'age'])
for i in range(1000):
conn.hset('hash2', 'egg_%s' % i, '鸡蛋%s号' % i)
count 数字是大致的 大小,如果拿了10 ,可能是9 可能是11
res=conn.hscan('hash2',cursor=0,count=10)
print(len(res[1]))
for item in conn.hscan_iter('hash2',count=10):
print(item)
conn.close()
常用的:
"""hset、hget、hlen、hexists、hincrby、hscan_iter"""
redis列表类型
'''
1 lpush(name, values)
2 rpush(name, values) 表示从右向左操作
3 lpushx(name, value)
4 rpushx(name, value) 表示从右向左操作
5 llen(name)
6 linsert(name, where, refvalue, value))
7 r.lset(name, index, value)
8 r.lrem(name, value, num)
9 lpop(name)
10 rpop(name) 表示从右向左操作
11 lindex(name, index)
12 lrange(name, start, end)
13 ltrim(name, start, end)
14 rpoplpush(src, dst)
15 blpop(keys, timeout)
16 r.brpop(keys, timeout),从右向左获取数据
17 brpoplpush(src, dst, timeout=0)
'''
import redis
conn = redis.Redis(decode_responses=True)
conn.lpush('girls', '刘亦菲', '迪丽热巴')
conn.rpush("girls", "小红")
conn.lpushx("girls", "小绿")
conn.rpush("girls", "小紫")
print(conn.llen("girls"))
conn.linsert("girls", "before", "小紫", "哈哈哈")
conn.lset('girls', 0, 'oooo')
conn.lrem('girls', 1, '刘亦菲')
conn.lrem('girls', -1, '刘亦菲')
conn.lrem('girls', 0, '刘亦菲')
print(conn.lpop('girls'))
print(conn.rpop('girls'))
print(conn.lindex('girls', 0))
print(conn.lrange('girls', 1, 10000))
conn.ltrim('girls', 2, 4)
conn.rpoplpush('girls', 'girls')
res = conn.blpop('girls', timeout=5)
print(res)
conn.close()
-使用生成器,写一个分批获取列表所有值的生成器
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具