提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
提示:以下是本篇文章正文内容,下面案例可供参考
一、redis相关操作
示例:。
二、使用步骤
1.引入库
代码如下(示例):
# -*- coding:utf-8 -*-
# author:
# datetime: 2024/3/1 15:02
# @File: 6redis相关操作2.py
# Redis 相关操作
import json
import redis
from logger import logger
class ReadisSaveConfig(object):
host = "127.0.0.1"
port = 6379
password = None
db_name = 15
pass
class RedisModel(object):
_pool = None
_isinstance = None
_flag = True
def __new__(cls, *args, **kwargs):
# if not cls._pool:
# print('new')
# cls._pool = redis.ConnectionPool(host='127.0.0.1')
# return super(RedisModel, cls).__new__(cls)
# return super().__new__(cls)
if not cls._isinstance:
print('new')
cls._pool = redis.ConnectionPool(host=ReadisSaveConfig.host, db=ReadisSaveConfig.db_name, socket_connect_timeout=10, max_connections=4, decode_responses=True)
cls._isinstance = super().__new__(cls)
return cls._isinstance
def __init__(self):
# print(f'standard_itmes 链接redis; db_name: {ReadisSaveConfig.db_name}')
self.redis_conn = redis.Redis(connection_pool=RedisModel._pool)
try:
self.redis_conn.ping() # 判断redis是否链接成功
except Exception as e:
logger.error(f"redis 链接失败 is: {str(e)}")
pass
def get(self):
print(self.redis_conn.get('xxx'))
print(type(self.redis_conn.get('xxx')))
def op_string(conn):
## 1 字符串操作
key1 = conn.get('key')
print(key1)
key2 = conn.incr('key') ## 自增1
print(key2)
ret3 = conn.incr('key')
print(ret3)
print(conn.decr('key')) # 自减去 1
print(conn.incr('key', 15))
print(conn.decr('key', 5))
print(conn.get('key'))
print(conn.set('key','13'))
print(conn.incr('key'))
print(conn.append('new-string-key', 'hello ')) ## 向字符串中拼接
print(conn.append('new-string-key', 'world!'))
print(conn.substr('new-string-key',3, 7)) # 取字符串的 3~7 的字符串结果
print(conn.get('new-string-key'))
print(conn.setrange('new-string-key', 0, 'H')) # 在0索引位置 设置'H'
print(conn.setrange('new-string-key', 6, 'W')) # 在6索引位置 设置'W'
print(conn.get('new-string-key'))
print(conn.setrange('new-string-key',11,', how are you?')) # 在某个范围内设置字符串
print(conn.get('new-string-key'))
print(conn.setbit('new-string-key',2,1))
print(conn.setbit('new-string-key',7,1))
def op_list(conn):
# 列表操作
print(conn.rpush('list-key', 'last')) # 右边推入数据
print(conn.lpush('list-key', 'first')) # 左边推入数据
print(conn.rpush('list-key', 'new last')) # 右边推入数据
print(conn.lrange('list-key', 0, -1)) # 查询所有数据
print(conn.lpop('list-key')) # 左边边删除数据
print(conn.lpop('list-key')) #
print(conn.lrange('list-key', 0, -1)) #
print(conn.rpush('list-key','a','b','c')) ## 同时推入多个
print(conn.lrange('list-key', 0, -1))
print(conn.ltrim('list-key', 2, -1)) # # 从左边删减两个
print(conn.lrange('list-key', 0, -1))
print(conn.rpush('list', 'item1'))
print(conn.rpush('list', 'item2'))
print(conn.rpush('list2', 'item3'))
print(conn.brpoplpush('list2', 'list', 1)) # 把list2的数据从右边的弹出,将数据从list左边推入
print(conn.lrange('list', 0, -1))
print(conn.brpoplpush('list', 'list2',1))
print(conn.lrange('list2', 0, -1))
print(conn.blpop(['list', 'list2'],1))
print(conn.lrange('list', 0, -1))
print(conn.lrange('list2', 0, -1))
pass
def op_set(conn):
pass
## 集合操作
print(conn.sadd('set-key','a','b','c'))
print(conn.srem('set-key','c','d')) # 删除 集合元素
# print(conn.srem('set-key','c','d'))
# print(conn.scard('set-key')) # 返回集合的数量
# print(conn.smembers('set-key')) # 获取集合元素
# print(conn.smove('set-key', 'set-key2', 'a')) # 将元素从一个集合移动到另一个集合('set-key2' 不存在会自动创建)
# print(conn.smove('set-key', 'set-key2', 'c')) # 将元素从一个集合移动到另一个集合 该元素不存在的话不会移动成功
# print(conn.sadd('skey1', 'a', 'b', 'c', 'd'))
# print(conn.sadd('skey2', 'c', 'd', 'e', 'f',))
# print(conn.sdiff('skey1', 'skey2')) # 查询在skey1里 不在skey2里的元素
# print(conn.sinter('skey1','skey2')) # 查询在两个集合中有的元素
# print(conn.sunion('skey1','skey2')) # 查询两个集合的并集
def op_hash(conn):
pass
# print(conn.hmset('hash-key', {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'})) # 批量设置
# print(conn.hmget('hash-key', ['k2', 'k3'])) # 批量获取
# print(conn.hlen('hash-key')) # 获取 'hash-key' 下有多少个键值对
# print(conn.hdel('hash-key', 'k1', 'k3')) # 删除 k1 k3 两个键值对
# print(conn.hmset('hash-keys2', {'short': 'hello', 'long': 1000 * '1'})) # 批量设置
# print(conn.hkeys('hash-keys2')) # 获取 'hash-keys2' 有多少key
# print(conn.hexists('hash-keys2','num')) #检查给定的键是否存在于散列
# print(conn.hincrby('hash-keys2','num')) # 对散列中尚未存在的键进行自增,redis会将键的值当0处理
# print(conn.hexists('hash-keys2','num')) #检查给定的键是否存在于散列
def op_zset(conn):
pass
# print(conn.zadd('zset-key', {'member': 1, 'member2': 2})) # 设置有序集合 {元素:分值}
# print(conn.zrange('zset-key', 0, -1)) # 获取有序集合成员列表
# print(conn.zcard('zset-key')) # 获取有序集合成员数量
# score = conn.zscore('zset-key', 'member') # 获取成员分数
# print(score)
#
# conn.zadd('zset-key',{'member':10}) # 更新成员分数
# score = conn.zscore('zset-key', 'member') # 获取成员分数
# print(score)
#
# # conn.zrem('zset-key','member') # 删除成员
# print(conn.zrange('zset-key', 0, -1)) # 获取有序集合成员列表
#
# rank = conn.zrank('zset-key','member')
# print(rank)
# score = conn.zscore('zset-key', 'member') # 获取成员分数
# print(score)
# conn.zincrby('zset-key',20,'member2') # 给成员进行自增操作
# print(conn.zcount('zset-key', 0, 30)) # 统计给定分值(0,30)范围内的元素数量;
# print(conn.zrange('zset-key', 0, -1, withscores=True)) # 获取有序集合成员列表
# print(conn.zscore('zset-key','member2')) # 获取分值
# conn.zadd('zset-1', {'a': 1, 'b': 2, 'c': 3}) # 添加集合
# conn.zadd('zset-2', {'b': 4, 'c': 1, 'd': 0}) # 添加集合
# conn.zinterstore('zset-i', ['zset-1', 'zset-2']) # 将有序集合成员的分值都加起来 存到新集合
# print(conn.zrange('zset-i', 0, -1, withscores=True))
#
conn.zunionstore('zset-u', ['zset-1', 'zset-2'], aggregate='min') # 求两个集合的并集有重复的元素取最小的元素值 生成到新的集合
print(conn.zrange('zset-u', 0, -1, withscores=True))
def op_sort(conn):
pass
# conn.rpush('sort-input', 23, 15, 110,7)
print(conn.sort('sort-input'))
print(conn.sort('sort-input',alpha=True))
conn.hset('d-7', 'field', 5)
conn.hset('d-15', 'field', 1)
conn.hset('d-23', 'field', 9)
conn.hset('d-110', 'field', 3)
print(conn.sort('sort-input', by='d-*->field')) # 将散列域(field)用作权重 对sort-input列表进行排序
print(conn.sort('sort-input', by='d-*->field', get='d-*->field')) # 获取外部数据,并将他们用作命令的返回值,而不是返回被排序的数据
# print(conn.hget('d-110', 'field'))
if __name__ == '__main__':
pass
data1 = {'name':'zs','age':18}
rdb = RedisModel()
redis_conn1 = rdb.redis_conn
# data =json.dumps(data1)
# try:
# redis_conn1.rpush("list_test222", data)
# except Exception as e:
# data1 = json.loads(data)
# logger.error(f"存入redis失败:{str(e)} ;data:{data1.get('studyUid', None)}")
# finally:
# print('关闭redis 链接')
# redis_conn1.close()
# # rdb.pool.release(rdb.redis_conn)
# op_set(redis_conn1)
rdb1 = RedisModel()
rdb2 = RedisModel()
print(id(rdb1) == id(rdb2))
#
pass