redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
1 安装使用Redis
1. 下载地址
https://redis.io/download
2. 启动服务端
# redis-server [--bind locahost_IP]
3. 启动客户端
# redis-cli
4. Python中操作Redis
pip install redis
2 Redis-py的API使用
2.1 操作模式
# redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py
import redis
# r = redis.StrictRedis(host='192.168.50.98', port=6379)
r = redis.Redis(host='192.168.50.98', port=6379)
r.set('foo', 'bar')
print(r.get('foo'))
2.2 连接池
# redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。
import redis
pool = redis.ConnectionPool(host='192.168.50.98', port= 6379)
r = redis.Redis(connection_pool=pool)
r.set('foo', 'bar')
print(r.get('foo'))
2.3 操作
- string: redis中的String在在内存中按照一个name对应一个value来存储。
1. SET key value [expiration EX seconds|PX milliseconds] [NX|XX]
在Redis中设置值,默认,不存在则创建,存在则修改
参数:
ex,过期时间(秒)
px,过期时间(毫秒)
nx,如果设置为True,则只有name不存在时,当前set操作才执行
xx,如果设置为True,则只有name存在时,当前set操作才执行
2. SETNX key value
summary: Set the value of a key, only if the key does not exist
3. SETEX key seconds value
summary: Set the value and expiration of a key
4. PSETEX key milliseconds value
summary: Set the value and expiration in milliseconds of a key
5. MSET key value [key value ...]
summary: Set multiple keys to multiple values
6. MGET key [key ...]
summary: Get the values of all the given keys
7. GETSET key value
summary: Set the string value of a key and return its old value
8. GETRANGE key start end
summary: Get a substring of the string stored at a key
9. SETRANGE key offset value
summary: Overwrite part of a string at key starting at the specified offset(新值太长时,则向后替换添加)
10. SETBIT key offset value
summary: Sets or clears the bit at offset in the string value stored at key
# offset,位的索引(将值变换成二进制后再进行索引)
# value,值只能是 1 或 0
# 可以用于用户状态记录如每一位二进制值表示一个用户,登陆值为1, 要计算用户登陆数目:
BITCOUNT key [start end]
summary: 获取key对应的值的二进制表示中 1 的个数,start,位起始位置,end,位结束位置
# 查看对应用户是否在线
GETBIT key offset
summary: Returns the bit value at offset in the string value stored at key
11. STRLEN key
summary: Get the length of the value stored in a key
12. INCR key
summary: Increment the integer value of a key by one
13. INCRBYFLOAT key increment
summary: Increment the float value of a key by the given amount
14. DECR key
summary: Decrement the integer value of a key by one
15. APPEND key value
summary: Append a value to a key
16. DEL key [key ...]
summary: Delete a key
- hash操作
1. HSET key field value
summary: Set the string value of a hash field
2. HGET key field
summary: Get the value of a hash field
3. HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values
4. HMGET key field [field ...]
summary: Get the values of all the given hash fields
5. HGETALL key
summary: Get all the fields and values in a hash
6. HLEN key
summary: Get the number of fields in a hash
7. HKEYS key
summary: Get all the fields in a hash
8. HVALS key
summary: Get all the values in a hash
9. HEXISTS key field
summary: Determine if a hash field exists
10. HINCRBY key field increment
summary: Increment the integer value of a hash field by the given number
11. HINCRBYFLOAT key field increment
summary: Increment the float value of a hash field by the given amount
12. HSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate hash fields and associated values
例:HSCAN hash1 0 match ke*
1) "0"
2) 1) "key1"
2) "11"
3) "key2"
4) "22"
5) "key3"
6) "33"
7) "key4"
8) "44"
- List操作,redis中的List在在内存中按照一个key对应一个value 来存储。
http://www.redis.cn/commands/lpop.html
> LPUSH list1 a b c
(integer) 3
> LLEN list1
(integer) 3
> LPOP list1
"c"
> LPOP list1
"b"
> LPOP list1
"a"
> LPOP list1
(nil)
1. LPUSH key value [value ...]
summary: Prepend one or multiple values to a list
2. LPUSHX key value
summary: Prepend a value to a list, only if the list exists
3. LLEN key
summary: Get the length of a list
4. LINSERT key BEFORE|AFTER pivot value
summary: Insert an element before or after another element in a list
5. LSET key index value
summary: Set the value of an element in a list by its index
6. LREM key count value
summary: Remove elements from a list
# 从存于 key 的列表里移除前 count 次出现的值为 value 的元素。 这个 count 参数通过下面几种方式影响这个操作:
count > 0: 从头往尾移除值为 value 的元素个数。
count < 0: 从尾往头移除值为 value 的元素个数。
count = 0: 移除所有值为 value 的元素。
需要注意的是,如果list里没有存在key就会被当作空list处理,所以当 key 不存在的时候,这个命令会返回 0。
7. LPOP key
summary: Remove and get the first element in a list
8. LINDEX key index
summary: Get an element from a list by its index
9. LRANGE key start stop
summary: Get a range of elements from a list
10. LTRIM key start stop
summary: Trim a list to the specified range
11. RPOPLPUSH source destination
summary: Remove the last element in a list, prepend it to another list and return it
12. BLPOP key [key ...] timeout
summary: Remove and get the first element in a list, or block until one is available
13. BRPOPLPUSH source destination timeout
summary: Pop a value from a list, push it to another list and return it; or block until one is available
- Set操作,Set集合就是不允许重复的列表
1. SADD key member [member ...]
summary: Add one or more members to a set
2. SCARD key
summary: Get the number of members in a set
3. SDIFF key [key ...]
summary: Subtract multiple sets
4. SDIFFSTORE destination key [key ...]
summary: Subtract multiple sets and store the resulting set in a key
5. SINTER key [key ...]
summary: Intersect multiple sets
6. SINTERSTORE destination key [key ...]
summary: Intersect multiple sets and store the resulting set in a key
7. SISMEMBER key member
summary: Determine if a given value is a member of a set
8. SMEMBERS key
summary: Get all the members in a set
9. SMOVE source destination member
summary: Move a member from one set to another
10. SPOP key [count]
summary: Remove and return one or multiple random members from a set
11. SRANDMEMBER key [count]
summary: Get one or multiple random members from a set
12. SREM key member [member ...]
summary: Remove one or more members from a set
13. SUNION key [key ...]
summary: Add multiple sets
14. SUNIONSTORE destination key [key ...]
summary: Add multiple sets and store the resulting set in a key
15. SSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate Set elements
- 有序集合,在集合的基础上,为每元素排序;元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值,即:分数和值,分数专门用来做排序。
1. ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
summary: Add one or more members to a sorted set, or update its score if it already exists
2. ZCARD key
summary: Get the number of members in a sorted set
3. ZCOUNT key min max
summary: Count the members in a sorted set with scores within the given values
4. ZINCRBY key increment member
summary: Increment the score of a member in a sorted set
5. ZRANGE key start stop [WITHSCORES]
summary: Return a range of members in a sorted set, by index
6. ZRANK key member
summary: Determine the index of a member in a sorted set
7. ZRANGEBYLEX key min max [LIMIT offset count]
summary: Return a range of members in a sorted set, by lexicographical range
8. ZREM key member [member ...]
summary: Remove one or more members from a sorted set
9. ZREMRANGEBYRANK key start stop
summary: Remove all members in a sorted set within the given indexes
10. ZREMRANGEBYSCORE key min max
summary: Remove all members in a sorted set within the given scores
11. ZREMRANGEBYLEX key min max
summary: Remove all members in a sorted set between the given lexicographical range
12. ZSCORE key member
summary: Get the score associated with the given member in a sorted set
13. ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
14. ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
summary: Add multiple sorted sets and store the resulting sorted set in a new key
15. ZSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate sorted sets elements and associated scores
- 其他操作
1. DEL key [key ...]
summary: Delete a key
2. DEL key [key ...]
summary: Delete a key
3. EXISTS key [key ...]
summary: Determine if a key exists
4. KEYS pattern
summary: Find all keys matching the given pattern
支持的正则表达模式:
h?llo 匹配 hello, hallo 和 hxllo
h*llo 匹配 hllo 和 heeeello
h[ae]llo 匹配 hello 和 hallo, 但是不匹配 hillo
h[^e]llo 匹配 hallo, hbllo, … 但是不匹配 hello
h[a-b]llo 匹配 hallo 和 hbllo
5. EXPIRE key seconds
summary: Set a key's time to live in seconds
6. RENAME key newkey
summary: Rename a key
7. MOVE key db
summary: Move a key to another database
8. RANDOMKEY -
summary: Return a random key from the keyspace
9. TYPE key
summary: Determine the type stored at key
10. SCAN cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate the keys space
- 管道
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
import redis
import time
pool = redis.ConnectionPool(host='192.168.50.98', port=6379)
r = redis.Redis(connection_pool=pool)
# pipe = r.pipeline(transaction=False)
pipe = r.pipeline()
pipe.set('name', 'abc')
time.sleep(30)
pipe.set('age', '22')
pipe.execute()
结果:
> get name
(nil)
> get age
(nil)
******waiting 30s 后同时输出*********
> get name
"abc"
> get age
"22"
2.4 发布订阅
redishelper
import redis
class RedisHelper:
def __init__(self):
self.__conn = redis.Redis(host='192.168.50.98')
self.chan_sub = 'fm104.5'
self.chan_pub = 'fm104.5'
def public(self, msg):
self.__conn.publish(self.chan_pub, msg)
return True
def subscribe(self):
# 打开收音机
pub = self.__conn.pubsub()
# 调频道
pub.subscribe(self.chan_sub)
# 准备接收
pub.parse_response()
return pub
publisher
from redishelper import RedisHelper
obj = RedisHelper()
obj.public('hello')
subscriber
from redishelper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.parse_response()
print(msg)