Redis安装
安装可用于Python编程语言操作的Redis库。
命令行安装方式如下:
pip install redis
连接Redis
Python Redis提供了两种连接方式:普通连接方式和连接池连接方式。
需要注意的是: Redis中字符串返回值类型是bytes类型
普通连接方式
redis_conn = redis.Redis(host='127.0.0.1', port=6379)
连接池连接方式
redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
redis_conn = redis.Redis(connection_pool=redis_pool)
5种数据类型操作
1 string字符串操作
1.设置和获取单个键值
设置单个键值
redis_conn.set("name_1", "张三")
获取单个键值
name_1 = redis_conn.get("name_1")
2.设置和获取多个键值
设置多个键值
redis_conn.mset(name_1='张三', name_2='李四')
或
names = {
'name_1': '张三',
'name_2': '李四'
}
redis_conn.mset(names)
获取多个键值
names = redis_conn.mget('name_1', 'name_2')
name_s = [str(name, 'utf-8') for name in names]
print(name_s)
2 list列表操作
1.左边添加值
sz = redis_conn.lpush("list_1", 1, 2, 3)
2.查询list长度
print(redis_conn.llen('list_1'))
3.下标范围查询
print(redis_conn.lrange('list_1', 0, 3))
4.指定下标查询
print(redis_conn.lindex('list_1', 1))
5.左边删除值
print(redis_conn.lpop('list_1'))
6.右边删除值
print(redis_conn.rpop('list_1'))
7.指定位置删除值
表示从坐标开始删除2个值为1的元素
print(redis_conn.lrem('list_1', 2, 1))
3 hash哈希操作
1.插入键值对
hset函数的参数有四个,前三个参数解释如下:
- name:hash表的名字,可以存储2^32 - 1个键值对
- key:键
- value:值
函数实现
def hset(self, name, key=None, value=None, mapping=None):
"""
Set ``key`` to ``value`` within hash ``name``,
``mapping`` accepts a dict of key/value pairs that will be
added to hash ``name``.
Returns the number of fields that were added.
For more information check https://redis.io/commands/hset
"""
if key is None and not mapping:
raise DataError("'hset' with no key value pairs")
items = []
if key is not None:
items.extend((key, value))
if mapping:
for pair in mapping.items():
items.extend(pair)
return self.execute_command("HSET", name, *items)
返回值是插入的条数,当已有该键时,返回0,表示插入失败
print(redis_conn.hset('hash_1', 'key_1', 'value_1'))
2.根据键查看值
print(redis_conn.hget('hash_1', 'key_1'))
3.查看指定hash表中的所有键
print(redis_conn.hkeys('hash_1'))
4.查看指定hash表中的所有值
print(redis_conn.hvals('hash_1'))
5.查看指定hash表中的所有键值对
print(redis_conn.hgetall('hash_1'))
6.查看指定hash表中元素个数
print(redis_conn.hlen('hash_1'))
4 set操作
1.添加数据
函数实现
def sadd(self, name, *values):
"""
Add ``value(s)`` to set ``name``
For more information check https://redis.io/commands/sadd
"""
return self.execute_command("SADD", name, *values)
添加数据
print(redis_conn.sadd('set_1', 'val_1', 'val_2', 'val_3'))
2.查看数据
print(redis_conn.smembers('set_1'))
3.查看数据个数
函数实现
def scard(self, name):
"""
Return the number of elements in set ``name``
For more information check https://redis.io/commands/scard
"""
return self.execute_command("SCARD", name)
print(redis_conn.scard('set_1'))
4.随机删除一个元素
函数实现
def spop(self, name, count=None):
"""
Remove and return a random member of set ``name``
For more information check https://redis.io/commands/spop
"""
args = (count is not None) and [count] or []
return self.execute_command("SPOP", name, *args)
print(redis_conn.scard('set_1'))
5.删除指定的元素
函数实现
def srem(self, name, *values):
"""
Remove ``values`` from set ``name``
For more information check https://redis.io/commands/srem
"""
return self.execute_command("SREM", name, *values)
print(redis_conn.srem('set_1', 'val_1', 'val_3'))
5 Zset操作
1.插入数据
mapping = {
'1': 10,
'1': 20,
'1': 30,
'2': 40,
'2': 50,
'3': 60
}
print(redis_conn.zadd('zset_1', mapping))
2.通过索引范围查看键
返回的keys
print(redis_conn.zrange('zset_1', 0, 3))
2.通过值的范围查看键
print(redis_conn.zrangebyscore('zset_1', 10, 60))
3.通过键删除数据
返回输出的个数
print(redis_conn.zrem('zset_1', '1', '2'))
4.通过索引范围删除数据
print(redis_conn.zremrangebyrank('zset_1', 1, 2))
5.通过分数范围删除数据
print(redis_conn.zremrangebyscore('zset_1', 10, 30))
全局关键字的操作
1.查看所有的key
print(redis_conn.keys())
2.查看key的类型
print(redis_conn.type('list_1'))
3.查看key是否存在
print(redis_conn.exists('list_1'))
4.删除键值对
print(redis_conn.delete('list_1'))
5.设置过期时间
函数实现
def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python timedelta object.
For more information check https://redis.io/commands/expire
"""
if isinstance(time, datetime.timedelta):
time = int(time.total_seconds())
return self.execute_command("EXPIRE", name, time)
设置成功返回True,超过设置时间后,该键值对就会被删除
print(redis_conn.expire('list_1', 10))
6.删除过期时间
函数实现
def persist(self, name):
"""
Removes an expiration on ``name``
For more information check https://redis.io/commands/persist
"""
return self.execute_command("PERSIST", name)
print(redis_conn.persist('myzset'))
7.查看过期剩余时间
def ttl(self, name):
"""
Returns the number of seconds until the key ``name`` will expire
For more information check https://redis.io/commands/ttl
"""
return self.execute_command("TTL", name)
print(redis_conn.ttl('myzset'))