简介
redis是以key-value格式存储数据的缓存数据库。它支持存储的value类型很多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。redis支持不同方式的排序,通过master-slave(主从)模式实现数据同步【备份】。
Redis优点:
-
异常快速 : Redis是非常快的,每秒可以执行大约110000设置操作,81000个/每秒的读取操作。
-
支持丰富的数据类型 : 如列表,集合,有序集合,哈希等数据类型。
-
操作都是原子的 : 所有 Redis 的操作都是原子,从而确保当两个客户同时访问 Redis 服务器得到的是更新后的值(最新值)。
- MultiUtility工具:Redis是一个多功能实用工具,可以在很多如:缓存,消息传递队列中使用(Redis原生支持发布/订阅),在应用程序中如:Web应用程序会话,网站页面点击数等任何短暂的数据。
- 单进程、单线程、持久化。
环境安装
建议在Linux系统操作,wins有很多意想不到的问题,4.0之后的版本不支持Windows系统,环境安装与服务启动具体操作步骤见: https://www.cnblogs.com/margret/p/17118784.html。
Redis API使用
redis-py 的API的使用可以分类为:
- 连接方式
- 连接池
- 操作
- String 操作
- Hash 操作
- List 操作
- Set 操作
- Sort Set 操作
- 管道
- 发布订阅
连接方式
import redis r = redis.Redis(host='127.0.0.1', port=6379) ###实例化对象 r.set('name', 'tester') ###设置key print(r.get('name'))
连接池
import redis pool = redis.ConnectionPool(host="127.0.0.1", port=6379, password="a12345678", max_connections=1000, db=0) ##Redis默认分库为0,支持最大分开数16 r =redis.Redis(connection_pool = pool) ##建立连接 r.set('name', 'tester') ###设置key print(r.get('name'))连接池
操作
String操作,模式key->value,常用命令如下:
1、set(name, value, ex=None, px=None, nx=False, xx=False)
在Redis中设置值,默认,不存在则创建,存在则修改 127.0.0.1:6379> help set SET key value [EX seconds] [PX milliseconds] [NX|XX] summary: Set the string value of a key since: 1.0.0 group: string 参数: ex,过期时间(秒) px,过期时间(毫秒) nx,如果设置为True,则只有name不存在时,当前set操作才执行 xx,如果设置为True,则只有name存在时,岗前set操作才执行 demo: ##设置key值过期为S 127.0.0.1:6379> set tester 111 ex 5 OK 127.0.0.1:6379> get tester "111" 127.0.0.1:6379> get tester (nil) ##设置key值过期为毫秒 127.0.0.1:6379> set tester 111 px 5000 OK 127.0.0.1:6379> get tester "111" 127.0.0.1:6379> get tester "111" 127.0.0.1:6379> get tester ##NX设置,key存在不修改不存在直接添加;xx相反操作 127.0.0.1:6379> set age 20 OK 127.0.0.1:6379> set age 18 NX (nil) 127.0.0.1:6379> keys * 1) "age" 2) "name" 127.0.0.1:6379> set age18 18 NX OK 127.0.0.1:6379> keys * 1) "age" 2) "age18" 3) "name" 127.0.0.1:6379>set命令
2、setnx(name, value):设置值,只有name不存在时,执行设置操作(添加)
###demo 127.0.0.1:6379> help setex SETEX key seconds value summary: Set the value and expiration of a key since: 2.0.0 group: string 127.0.0.1:6379> setex age 8 15 ###8位过期时间,15新赋值 OK 127.0.0.1:6379> get age "15" 127.0.0.1:6379> get age "15" 127.0.0.1:6379> get age (nil) 127.0.0.1:6379>demo
3、setex(name, value, time):# time,给key设置过期时间(数字秒 或 timedelta对象)
127.0.0.1:6379> help setex SETEX key seconds value summary: Set the value and expiration of a key since: 2.0.0 group: string 127.0.0.1:6379> setex color 6 "red" OK 127.0.0.1:6379> get color "red" 127.0.0.1:6379> get color (nil)给key设置过期时间
4、mset(*args, **kwargs):批量设置值;mget(keys, *args):批量获取
127.0.0.1:6379> help mset MSET key value [key value ...] summary: Set multiple keys to multiple values since: 1.0.1 group: string 127.0.0.1:6379> mset k1 'v1' k2 'v2' OK 127.0.0.1:6379> mget k1 k2 1) "v1" 2) "v2"批量设置值与批量查看
5、getset(name, value):设置新值并获取原来的值
127.0.0.1:6379> help getset GETSET key value summary: Set the string value of a key and return its old value since: 1.0.0 group: string 127.0.0.1:6379> getset k1 "678" "abc" 127.0.0.1:6379> get k1 "678" 127.0.0.1:6379>View Code
6、getrange(key, start, end):获取子序列(根据字节获取,非字符),即相当于Python切片
参数: # name,Redis 的 name # start,起始位置(字节) # end,结束位置(字节) 127.0.0.1:6379> help getrange GETRANGE key start end summary: Get a substring of the string stored at a key since: 2.4.0 group: string 127.0.0.1:6379> getrange name 0 3 "test" 127.0.0.1:6379> getrange name 1 5 "ester"View Code
7、setrange(name, offset, value):修改字符串内容,从指定字符串索引开始向后替换(新值太长时,则向后添加)
127.0.0.1:6379> gerrange name 0 -1 (error) ERR unknown command 'gerrange' 127.0.0.1:6379> help setrange SETRANGE key offset value summary: Overwrite part of a string at key starting at the specified offset since: 2.2.0 group: string 127.0.0.1:6379> getrange name 0 -1 "tester gao" 127.0.0.1:6379> setrange name 0 H (integer) 10 127.0.0.1:6379> getrange name 0 -1 "Hester gao" 127.0.0.1:6379> setrange name 2 Sh (integer) 10 127.0.0.1:6379> getrange name 0 -1 "HeSher gao" 127.0.0.1:6379> setrange name 1 333 (integer) 10 127.0.0.1:6379> getrange name 0 -1 "H333er gao"View Code
8、setbit(name, offset, value):name对应值的二进制表示的位进行操作
参数: # name,redis的name # offset,位的索引(将值变换成二进制后再进行索引) # value,值只能是 1 或 0 # demo:如果在Redis中有一个对应: n1 = "foo", 那么字符串foo的二进制表示为:01100110 01101111 01101111 所以,如果执行 setbit('n1', 7, 1),则就会将第7位设置为1, 那么最终二进制则变成 01100111 01101111 01101111,即:"goo" # 扩展,转换二进制表示: source = "foo" for i in source: num = ord(i) ###获取ASCII对应的值 print(bin(num).replace('b','')) ###转换成二进制 特别的,如果source是汉字 "吴淞"怎么办? 答:对于utf-8,每一个汉字占3个字节,那么 "吴淞" 则有 9个字节 对于汉字,for循环时候会按照 字节 迭代,那么在迭代时,将每一个字节转换 十进制数,然后再将十进制数转换成二进制 11100110 10101101 10100110 11100110 10110010 10011011 11101001 10111101 10010000 s = "吴淞" bin_list = [bin(int(hex(x),16)) for x in bytes(s, 'utf-8')]View Code
*用途举例,用最省空间的方式,存储在线用户数及分别是哪些用户在线
解答思路【多用于门户网站的统计】:
127.0.0.1:6379> set usercount 0 ###设置用户统计数变量,ASCII为0的数不会表示 先用0替代然后计算0含有的二进制中1的个数,然后减去 OK 127.0.0.1:6379> bitcount usercount ###查看用户统计数二进制含有1的个数,到时减去初始值 (integer) 2 127.0.0.1:6379> setbit usercount 101 1 ###uid为101的登录用户统计到usercount,为1代表登录 0未登录【不需要设置】 (integer) 0 127.0.0.1:6379> setbit usercount 201 1 ###uid为201的用户登录 (integer) 0 127.0.0.1:6379> setbit usercount 301 1 ###uid为301的用户登录 (integer) 0 127.0.0.1:6379> bitcount usercount ##查询用户当前登录数(别忘记减去初始值,如果usercount ASCII值能设置成0即不用减) (integer) 5 127.0.0.1:6379> getbit usercount 201 ##查看201用户是否登录 (integer) 1 ##登录 127.0.0.1:6379> getbit usercount 202 ###查看201用户是否登录 (integer) 0 ###未登录
9、bitcount(key, start=None, end=None):获取key对应的值的二进制表示中 1 的个数
bitcount(key, start=None, end=None) # 参数: # key,Redis的name # start,位起始位置 # end,位结束位置 127.0.0.1:6379> help bitcount BITCOUNT key [start] [end] summary: Count set bits in a string since: 2.6.0 group: string 127.0.0.1:6379> bitcount name (integer) 37View Code
10、setbit(key, start=None, end=None):修改key对应的值的二进制值
127.0.0.1:6379> get name "H333er gao" 127.0.0.1:6379> setbit name 11 1 (integer) 1 127.0.0.1:6379> get name "H333er gao" 127.0.0.1:6379> setbit name 3 1 (integer) 0 127.0.0.1:6379> get name "X333er gao"View Code
11、append(key,value):用于为指定的 key 追加值
127.0.0.1:6379> help append APPEND key value summary: Append a value to a key since: 2.0.0 group: string 127.0.0.1:6379> get name "X333er gaowang" 127.0.0.1:6379> append name queen (integer) 19 127.0.0.1:6379> get name "X333er gaowangqueen"View Code
Hash操作:
1、hmset(name, mapping):批量设置
127.0.0.1:6379> help hmset HMSET key field value [field value ...] summary: Set multiple hash fields to multiple values since: 2.0.0 group: hash 127.0.0.1:6379> hmset info name alex age 55 hobby money weather 35000000 ##批量设置变量,存在info健中 OK 127.0.0.1:6379> hget info name age hobby weather (error) ERR wrong number of arguments for 'hget' command 127.0.0.1:6379> hmget info name age hobby weather ###批量获取变量值 1) "alex" 2) "55" 3) "money" 4) "35000000" 127.0.0.1:6379> hget info name ###取单个值 "alex"View Code
2、hset(name, key, value):单个设置
127.0.0.1:6379> help hset HSET key field value summary: Set the string value of a hash field since: 2.0.0 group: hash 127.0.0.1:6379> hset windy level 5 (integer) 1 127.0.0.1:6379> hset windy cooler 11 (integer) 1 127.0.0.1:6379> hget windy level "5"View Code
3、hget(name,key):单个获取key值,见hset操作
4、hmget(name, keys, *args):批量获取key值,见hmset操作
5、hexists(name, key):判断元素是否存在
127.0.0.1:6379> help hexists HEXISTS key field summary: Determine if a hash field exists since: 2.0.0 group: hash 127.0.0.1:6379> hexists windy level (integer) 1 127.0.0.1:6379> hexists windy level33 (integer) 0 127.0.0.1:6379>View Code
6、hgetall:获取全部key对应的值
127.0.0.1:6379> help hgetall HGETALL key summary: Get all the fields and values in a hash since: 2.0.0 group: hash 127.0.0.1:6379> hgetall windy 1) "level" 2) "5" 3) "cooler" 4) "11"View Code
7、hscan(name, cursor=0, match=None, count=None):匹配name对应的所有hash值
127.0.0.1:6379> help hscan HSCAN key cursor [MATCH pattern] [COUNT count] summary: Incrementally iterate hash fields and associated values since: 2.8.0 group: hash 127.0.0.1:6379> hscan info 0 1) "0" 2) 1) "name" 2) "alex" 3) "age" 4) "55" 5) "hobby" 6) "money" 7) "weather" 8) "35000000" 127.0.0.1:6379> hscan info 0 match m* 1) "0" 2) (empty list or set) 127.0.0.1:6379> hscan info 0 match *m* 1) "0" 2) 1) "name" ##key 2) "alex" ##value 127.0.0.1:6379> hscan info 0 match *g* 1) "0" 2) 1) "age" ##key 2) "55" ##value 127.0.0.1:6379> hscan info 0 match *w* 1) "0" 2) 1) "weather" 2) "35000000" 127.0.0.1:6379> hscan info 0 match *o* 1) "0" 2) 1) "hobby" 2) "money"View Code
List 操作
1、lpush(name,values) :在name对应的list中添加元素,每个新的元素都添加到列表的最左边
127.0.0.1:6379> help lpush LPUSH key value [value ...] summary: Prepend one or multiple values to a list since: 1.0.0 group: list 127.0.0.1:6379> lrange t_list 0 -1 (empty list or set) 127.0.0.1:6379> lpush t_list t1 t2 t3 t5 t6 (integer) 5 127.0.0.1:6379> lrange t_list 0 -1 1) "t6" 2) "t5" 3) "t3" 4) "t2" 5) "t1" 127.0.0.1:6379> lpush t_list t11 t22 t33 t55 t66 (integer) 10 127.0.0.1:6379> lrange t_list 0 -1 1) "t66" 2) "t55" 3) "t33" 4) "t22" 5) "t11" 6) "t6" 7) "t5" 8) "t3" 9) "t2" 10) "t1"View Code
2、lpushx(name,value):在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边
效果等同lpush,但一次只能追加一个元素 127.0.0.1:6379> help lpushx LPUSHX key value summary: Prepend a value to a list, only if the list exists since: 2.2.0 group: list 127.0.0.1:6379> lpushx sss 111 333 ##sss不存在追加不了 (error) ERR wrong number of arguments for 'lpushx' command 127.0.0.1:6379> lpushx st_list st777 st888 ###st_list存在但一次只能追加一个元素 (error) ERR wrong number of arguments for 'lpushx' command 127.0.0.1:6379> lpushx st_list3 st777 ##st_list3不存在追加不了,但不报错 (integer) 0 127.0.0.1:6379> lrange lst_list3 0 -1 ##st_list3为空 (empty list or set) 127.0.0.1:6379> lpushx st_list st-12 ##st_list已存在的key添加一个元素,成功 (integer) 6 127.0.0.1:6379> lrange st_list 0 -1 1) "st-12" 2) "st888" 3) "st777" 4) "s3" 5) "s2" 6) "s1" 127.0.0.1:6379> lpushx st_list st-11 st-13 ####st_list已存在的key添加多个元素,失败 (error) ERR wrong number of arguments for 'lpushx' commandView Code
3、linsert(name, where, refvalue, value)):往列表的指定元素位置添加元素
127.0.0.1:6379> help linsert LINSERT key BEFORE|AFTER pivot value summary: Insert an element before or after another element in a list since: 2.2.0 group: list 127.0.0.1:6379> lrange st_list 0 -1 1) "st-12" 2) "st888" 3) "st777" 4) "s3" 5) "s2" 6) "s1" 127.0.0.1:6379> linsert st_list before st777 ss111 (integer) 7 127.0.0.1:6379> lrange st_list 0 -1 1) "st-12" 2) "st888" 3) "ss111" 4) "st777" 5) "s3" 6) "s2" 7) "s1"View Code
4、lpop(name):从左边删除一个元素
127.0.0.1:6379> help lpop LPOP key summary: Remove and get the first element in a list since: 1.0.0 group: list 127.0.0.1:6379> lpop st_list2 (nil) 127.0.0.1:6379> lpop st_list "st-12" 127.0.0.1:6379> lpop st_list "st888"View Code
5、lset(key, index, value):指定位置修改值
127.0.0.1:6379> help lset LSET key index value summary: Set the value of an element in a list by its index since: 1.0.0 group: list 127.0.0.1:6379> lrange st_list 0 -1 1) "ss111" 2) "st777" 3) "s3" 4) "s2" 5) "s1" 127.0.0.1:6379> lset st_list 3 pig_s ###index下标从0开始 OK 127.0.0.1:6379> lrange st_list 0 -1 1) "ss111" 2) "st777" 3) "s3" 4) "pig_s" 5) "s1"View Code
6、ltrim(name, start, end):切片,指定索引范围保留,其余头和尾去掉。
127.0.0.1:6379> help ltrim LTRIM key start stop summary: Trim a list to the specified range since: 1.0.0 group: list 127.0.0.1:6379> ltrim st_list 1 3 OK 127.0.0.1:6379> lrange st_list 0 -1 1) "st777" 2) "s3" 3) "pig_s"View Code
set集合操作,不允许重复的列表
1、sadd(name,values):往name对应的集合中添加元素
smembers(name):查看name对应集合元素
127.0.0.1:6379> help sadd SADD key member [member ...] summary: Add one or more members to a set since: 1.0.0 group: set 127.0.0.1:6379> sadd s_set 1 2 3 4 5 6 7 8 9 99 1 2 (integer) 10 127.0.0.1:6379> smembers s_set 1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "99"View Code
2、sdiffstore(dest, keys, *args):求差集
127.0.0.1:6379> sadd s_set1 1 2 3 5 6 7 9 11 15 18 66 (integer) 11 127.0.0.1:6379> sadd s_set2 5 6 2 4 8 9 127.0.0.1:6379> sdiffstore c_set s_set1 s_set2 (integer) 7 127.0.0.1:6379> smembers c_set 1) "1" 2) "3" 3) "7" 4) "11" 5) "15" 6) "18" 7) "66"View Code
3、sinterstore(dest, keys, *args):交集
127.0.0.1:6379> sadd s_set1 1 2 3 5 6 7 9 11 15 18 66 (integer) 11 127.0.0.1:6379> sadd s_set2 5 6 2 4 8 9 127.0.0.1:6379> sinterstore j_set s_set1 s_set2 (integer) 4 127.0.0.1:6379> smembers j_set 1) "2" 2) "5" 3) "6" 4) "9"View Code
4、sunionstore(dest,keys, *args):并集
127.0.0.1:6379> sadd s_set1 1 2 3 5 6 7 9 11 15 18 66 (integer) 11 127.0.0.1:6379> sadd s_set2 5 6 2 4 8 9 (integer) 6 127.0.0.1:6379> sunionstore b_set s_set1 s_set2 (integer) 13 127.0.0.1:6379> smembers b_set 1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "11" 11) "15" 12) "18" 13) "66"View Code
其它常用命令
1、del(*names):删除指定元素 del k1 k2
2、exists(name):判断元素是否存在
127.0.0.1:6379> help exists EXISTS key summary: Determine if a key exists since: 1.0.0 group: generic 127.0.0.1:6379> exists windy (integer) 1 127.0.0.1:6379> exists windy33 (integer) 0View Code
3、keys(pattern='*'):查看所有元素
127.0.0.1:6379> keys * 1) "usercount" 2) "b_set" 3) "windy" 4) "st_list" 5) "c_set" 6) "name,"View Code
4、select(db=0):选择分库,redis默认库为0,最大支持16个分库,选择分库通过这个命令
5、move(name, db)):将redis的某个值移动到指定的db下
127.0.0.1:6379> select 1 OK 127.0.0.1:6379[1]> keys * (empty list or set) 127.0.0.1:6379[1]> select 0 OK 127.0.0.1:6379> move s_set 1 (integer) 1 127.0.0.1:6379> select 1 OK 127.0.0.1:6379[1]> keys * 1) "s_set"指定元素移库
管道
#!/usr/bin/env python # -*- coding:utf-8 -*- ##redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,设置transaction=True实现一次请求指定多个命令而不需要反复创建断开连接,并且默认情况下一次pipline 是原子性操作。 import redis pool = redis.ConnectionPool(host="127.0.0.1", port=6379, password="a12345678", max_connections=1000, db=0) r = redis.Redis(connection_pool=pool) # pipe = r.pipeline(transaction=False) pipe = r.pipeline(transaction=True) pipe.set('name', 'alex') pipe.set('role', 'sb') pipe.execute()管道连接
标签:127.0,name,0.1,list,Redis,6379,key,常用命令,操作 From: https://www.cnblogs.com/margret/p/17159076.html