redis存储系统

redis存储系统

1.什么是redis

REmote DIctionary Server(Redis) 是一个key-value存储系统。使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API(python, php, java…)。

它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

Redis的优势

  • 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s
  • 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作
  • 原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来
  • Redis支持数据的备份,即master-slave模式的数据备份
  • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用

2.redis的安装

  • 安装python包

方法1:pycharm中的setting中的pip中直接下载
方法2:命令下载(linux的shell中)

Su  #切换到超级用户
Cd /usr/local/python3/bin
./pip install redis
./pip3 install -U pip  #升级pip
  • 安装redis服务

下载地址:http://redis.io/download,下载最新稳定版本

tar zxf redis-5.0.3.tar.gz
cd redis-5.0.3/
yum install gcc -y
make
make install
cd utils/
./install_server.sh
netstat -antlp|grep 6379
redis-cli
 /etc/init.d/redis_6379 restart

3.redis的连接

方法1:这种方法连接一次就会自动断开

import redis
import time


redis.Redis(host='localhost',port=6379)
conn = redis.Redis()
conn.set('name','westos',3)
print(conn.get('name'))
print('等待3秒...')
time.sleep(3)
print(conn.get('name'))

在这里插入图片描述
方法2:不会自动断开连接,相对于第一种方法来说较为稳定

pool = redis.ConnectionPool(host='localhost',port=6379)
conn = redis.Redis(connection_pool=pool)
# 默认返回bytes类型 如果需要转换 要解码为utf=8编码格式
conn.set('name','粉条',4)
print(conn.get('name').decode('utf-8'))
print('等待3s....')
time.sleep(3)
print(conn.get('name'))

在这里插入图片描述

4.redis的具体使用

上传/获取/清除

import redis
import time

pool = redis.ConnectionPool(host='localhost',port=6379)
conn = redis.Redis(connection_pool=pool)
conn.set('name','fentiao')
conn.set('age',10)
conn.set('score',100)

# 获取所有的key值
print(conn.keys())
print(len(conn.keys()))
# 当前redis数据库中的数据条数
print(conn.dbsize())
# 删除指定的key-value值
conn.delete('score')
print('正在删除key....')
print(conn.get('score'))

print('清除前:',conn.keys())
# 清除redis里面的所有k-v
conn.flushall()
print('清除后:',conn.keys())

在这里插入图片描述

发布了97 篇原创文章 · 获赞 22 · 访问量 3252

猜你喜欢

转载自blog.csdn.net/nigar_/article/details/104118264