Pyhton浅谈-Python操作数据库之Redis(3)
一、Redis简介:
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取
交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作
写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
二、Redis的特点:
- 速度快
- 持久化
- 多种数据结构
- 支持多种编程语言
- 功能丰富
- 简单:代码短小精悍
- 主从复制
- 高可用、分布式
三、Redis的Windwos版本下载:
https://github.com/microsoftarchive/redis/releases
四、Redis 的简单使用:
C:\Program Files\Redis>redis-cli.exe # CMD命令行打开redis-cli—默认路径 127.0.0.1:6379> set name catt1e # 创建字符串 OK 127.0.0.1:6379> set age 18 OK 127.0.0.1:6379> get name # 查看字符串 "catt1e" 127.0.0.1:6379> get age "18" 127.0.0.1:6379> set 'city' 'beijing' # KV对应 OK 127.0.0.1:6379> get city "beijing" 127.0.0.1:6379> keys * # 查看输入的关键字 1) "age" 2) "city" 3) "name" 127.0.0.1:6379> dbsize # 查看输入的关键字的多少 (integer) 3 127.0.0.1:6379> set name catt1e EX 20 # 设置字符串存活时间 OK 127.0.0.1:6379> ttl name (integer) 17 127.0.0.1:6379> ttl name (integer) 12
五、Python简单操作—redis:
以下代码为ipython演示:
import redis # 导入python库 In [2]: client = redis.StrictRedis() # 实例化对象 In [3]: client.set('name', 'catt1e') # 创建字符串 Out[3]: True In [4]: client.get('name') # 查看字符串,默认为字节流的方式 Out[4]: b'catt1e' In [6]: client.incr('catt1e:home') # 使用incr()方法的自增特点 Out[6]: 1 In [7]: client.incr('catt1e:home') Out[7]: 2 In [8]: client.incr('catt1e:home') Out[8]: 3 In [9]: client.incr('catt1e:home') Out[9]: 4 In [10]: client.incr('catt1e:home') Out[10]: 5 In [11]: client.get('catt1e:home') Out[11]: b'5' ## 练习函数:主要功能为记载用户访问网页的次数并且可以查询 In [27]: class PageCount: ...: def __init__(self, host ='localhost', port='6379'): ...: self.client = redis.StrictRedis(host, port) ...: def count_page(self, user, page='home'): ...: self.client.incr(user + ':' + page) ...: def query_page(self, user, page='hoem'): ...: try: ...: count = self.client.get(user + ':' + page) ...: return int(count) ...: except Exception as e: ...: print(f'{user}没来过{page}这个页面....') ...: return ...: In [28]: page = PageCount() In [29]: page.count_page('jay') In [30]: page.count_page('jay') In [31]: page.count_page('jay') In [32]: page.count_page('jay') In [33]: page.get_page('jay') In [34]: page.query_page('jay') jay没来过hoem这个页面.... In [35]: page.query_page('jay', 'home') Out[35]: 4