Python操作redis的方法

這篇文章將為大家詳細講解有關(guān)Python操作redis的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),三水企業(yè)網(wǎng)站建設(shè),三水品牌網(wǎng)站建設(shè),網(wǎng)站定制,三水網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,三水網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。

python3操作redis

redis也被稱為緩存

1.redis是一個key-value存儲系統(tǒng),沒有ForeignKey和ManyToMany的字段。
2.在redis中創(chuàng)建的數(shù)據(jù)彼此之間是沒有關(guān)系的,所以也被稱為是非關(guān)系型數(shù)據(jù)庫。
3.它支持存儲包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set --有序集合)和hash(哈希類型)等數(shù)據(jù)類型。
4.redis支持的數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原子性的。
5.redis支持各種不同方式的排序。為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。
6.redis會周期性的把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎(chǔ)上實現(xiàn)了master-slave(主從)同步。

在正常的服務(wù)器中,redis是運行在內(nèi)存中的,而數(shù)據(jù)庫是運行在服務(wù)器的硬盤上的。

因為內(nèi)存的運行速度遠遠快于硬盤的轉(zhuǎn)速,所以redis查詢速度遠快于保存在硬盤的數(shù)據(jù)庫。

同樣,因為redis是保存在內(nèi)存中的,一臺服務(wù)器可以配置非常大的硬盤,相對于硬盤來說,服務(wù)器內(nèi)存的配置容量遠小于配置的硬盤容量,

所以redis有一定的容量限制,同樣因為redis是保存在內(nèi)存中的,所以服務(wù)器一旦斷電,redis中保存的數(shù)據(jù)很容易丟失。

redis中存放的是常用的,且不經(jīng)常更新的數(shù)據(jù)。

一臺服務(wù)器剛上線的時候,用戶訪問服務(wù)器上的數(shù)據(jù)的時候,先去緩存中看看是否有要查詢的數(shù)據(jù)。

如果緩存中保存有用戶需要的數(shù)據(jù),則直接從緩存中獲取需要的數(shù)據(jù);
如果緩存中沒有用戶需要的數(shù)據(jù),則會從數(shù)據(jù)庫中查詢數(shù)據(jù)并返回給用戶,同時會把這些數(shù)據(jù)在內(nèi)存中保存一份;
這樣下一位用戶再來訪問同樣的數(shù)據(jù)時,則會直接從緩存中讀取需要的數(shù)據(jù),而不用訪問數(shù)據(jù)庫,加快了用戶的訪問速度。

例如,我們在博客園發(fā)表一篇博客時,在博客園的首頁不會立即出現(xiàn)剛才所發(fā)表的那篇博客,而是要等幾分鐘之后,在博客園的首頁才會出現(xiàn)剛才發(fā)表的那篇博客文章,這就是因為緩存的原因。

1.準(zhǔn)備工作

為CentOS系統(tǒng)配置好epel源。

2.安裝Redis

[root@bogon yum.repos.d]# yum list | grep redis
Repository base is listed more than once in the configuration
Repository updates is listed more than once in the configuration
Repository extras is listed more than once in the configuration
Repository centosplus is listed more than once in the configuration
redis.x86_64                            3.2.10-2.el7                   @epel    
collectd-redis.x86_64                   5.7.1-2.el7                    epel     
collectd-write_redis.x86_64             5.7.1-2.el7                    epel     
hiredis.x86_64                          0.12.1-1.el7                   epel     
hiredis-devel.x86_64                    0.12.1-1.el7                   epel     
opensips-redis.x86_64                   1.10.5-3.el7                   epel     
pcp-pmda-redis.x86_64                   3.11.8-7.el7                   base     
php-nrk-Predis.noarch                   1.0.4-1.el7                    epel     
php-pecl-redis.x86_64                   2.2.8-1.el7                    epel     
php-phpiredis.x86_64                    1.0.0-2.el7                    epel     
python-redis.noarch                     2.10.3-1.el7                   epel     
python-trollius-redis.noarch            0.1.4-2.el7                    epel     
python2-django-redis.noarch             4.3.0-1.el7                    epel     
redis-trib.noarch                       3.2.10-2.el7                   epel     
rubygem-redis.noarch                    3.2.1-2.el7                    epel     
rubygem-redis-doc.noarch                3.2.1-2.el7                    epel     
syslog-ng-redis.x86_64                  3.5.6-3.el7                    epel     
uwsgi-logger-redis.x86_64               2.0.15-1.el7                   epel     
uwsgi-router-redis.x86_64               2.0.15-1.el7                   epel     
[root@bogon yum.repos.d]# yum install -y redis
Loaded plugins: fastestmirror, langpacks
Repository base is listed more than once in the configuration
Repository updates is listed more than once in the configuration
Repository extras is listed more than once in the configuration
Repository centosplus is listed more than once in the configuration
Loading mirror speeds from cached hostfile
 * epel: ftp.cuhk.edu.hk
Package redis-3.2.10-2.el7.x86_64 already installed and latest version
Nothing to do

3.redis的文件目錄結(jié)構(gòu)

使用rpm -ql命令查看redis安裝之后在系統(tǒng)中生成的文件

[root@bogon ~]# rpm -ql redis
/etc/logrotate.d/redis
/etc/redis-sentinel.conf            # redis的守護配置文件
/etc/redis.conf                 # redis的配置文件
/etc/systemd/system/redis-sentinel.service.d
/etc/systemd/system/redis-sentinel.service.d/limit.conf
/etc/systemd/system/redis.service.d
/etc/systemd/system/redis.service.d/limit.conf
/usr/bin/redis-benchmark
/usr/bin/redis-check-aof
/usr/bin/redis-check-rdb
/usr/bin/redis-cli                  # redis的交互式命令行界面
/usr/bin/redis-sentinel         # redis的守護文件
/usr/bin/redis-server           # redis的服務(wù)端啟動文件
/usr/lib/systemd/system/redis-sentinel.service  # redis的守護程序的函數(shù)庫文件
/usr/lib/systemd/system/redis.service           # redis的函數(shù)庫文件
/usr/libexec/redis-shutdown     # 停止redis的執(zhí)行文件
/usr/share/doc/redis-3.2.10     # redis的幫助文件
/usr/share/doc/redis-3.2.10/00-RELEASENOTES
/usr/share/doc/redis-3.2.10/BUGS
/usr/share/doc/redis-3.2.10/CONTRIBUTING
/usr/share/doc/redis-3.2.10/MANIFESTO
/usr/share/doc/redis-3.2.10/README.md
/usr/share/licenses/redis-3.2.10            # redis的licenses說明
/usr/share/licenses/redis-3.2.10/COPYING
/usr/share/man/man1/redis-benchmark.1.gz    # redis的man文件
/usr/share/man/man1/redis-check-aof.1.gz
/usr/share/man/man1/redis-check-rdb.1.gz
/usr/share/man/man1/redis-cli.1.gz
/usr/share/man/man1/redis-sentinel.1.gz
/usr/share/man/man1/redis-server.1.gz
/usr/share/man/man5/redis-sentinel.conf.5.gz
/usr/share/man/man5/redis.conf.5.gz
/var/lib/redis                          # redis的持久化文件保存路徑
/var/log/redis                          # redis的日志文件
/var/run/redis                          # redis的進程PID文件

4.redis的啟動停止與狀態(tài)查看

[root@bogon ~]# systemctl status redis.service      # 查看redis的狀態(tài),可以看到是活動狀態(tài)
● redis.service - Redis persistent key-value database
 Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/redis.service.d
     └─limit.conf
 Active: active (running) since Thu 2017-11-16 17:29:39 CST; 1min 44s ago
Process: 6272 ExecStop=/usr/libexec/redis-shutdown (code=exited, status=0/SUCCESS)
Main PID: 6286 (redis-server)
 CGroup: /system.slice/redis.service
     └─6286 /usr/bin/redis-server 0.0.0.0:6379
Nov 16 17:29:39 bogon systemd[1]: Started Redis persistent key-value database.
Nov 16 17:29:39 bogon systemd[1]: Starting Redis persistent key-value database...
[root@bogon ~]# systemctl stop redis.service      # 停止redis
[root@bogon ~]# systemctl status redis.service      # redis牌非活動狀態(tài)
● redis.service - Redis persistent key-value database
 Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/redis.service.d
     └─limit.conf
 Active: inactive (dead)
Nov 16 17:21:56 bogon systemd[1]: redis.service: control process exited, code=exited status=1
Nov 16 17:21:56 bogon systemd[1]: Unit redis.service entered failed state.
Nov 16 17:21:56 bogon systemd[1]: redis.service failed.
Nov 16 17:22:04 bogon systemd[1]: Started Redis persistent key-value database.
Nov 16 17:22:04 bogon systemd[1]: Starting Redis persistent key-value database...
Nov 16 17:29:39 bogon systemd[1]: Stopping Redis persistent key-value database...
Nov 16 17:29:39 bogon systemd[1]: Started Redis persistent key-value database.
Nov 16 17:29:39 bogon systemd[1]: Starting Redis persistent key-value database...
Nov 16 17:31:38 bogon systemd[1]: Stopping Redis persistent key-value database...
Nov 16 17:31:38 bogon systemd[1]: Stopped Redis persistent key-value database.
[root@bogon yum.repos.d]# redis-server        # 啟動redis程序
5587:C 16 Nov 15:42:56.010 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
5587:M 16 Nov 15:42:56.018 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.2.10 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 6519
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                        
5587:M 16 Nov 15:42:56.022 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
5587:M 16 Nov 15:42:56.022 # Server started, Redis version 3.2.10
5587:M 16 Nov 15:42:56.022 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
5587:M 16 Nov 15:42:56.025 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
5587:M 16 Nov 15:42:56.026 * The server is now ready to accept connections on port 6379
[root@bogon ~]# systemctl status redis.service
● redis.service - Redis persistent key-value database
 Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/redis.service.d
     └─limit.conf
 Active: active (running) since Thu 2017-11-16 17:31:47 CST; 2s ago
Main PID: 6325 (redis-server)
 CGroup: /system.slice/redis.service
     └─6325 /usr/bin/redis-server 0.0.0.0:6379
Nov 16 17:31:47 bogon systemd[1]: Started Redis persistent key-value database.
Nov 16 17:31:47 bogon systemd[1]: Starting Redis persistent key-value database...

redis的啟動方式有兩種:

[root@bogon ~]# systemctl start redis.service   # 后臺啟動,無歡迎界面
[root@bogon ~]# redis-server            # 前臺啟動,可以看到歡迎界面

redis的停止方式有兩種:

[root@bogon ~]# systemctl stop redis.service
[root@bogon ~]# /usr/libexec/redis-shutdown

5.redis的主配置文件說明

bind 127.0.0.1                          # redis綁定的主機地址,這里默認僅支持本地連接
protected-mode yes                      # 是否以保護模式運行redis
port 6379                               # 指定redis監(jiān)聽的端口
tcp-backlog 511
timeout 0                               # 客戶端閑置多長時間后關(guān)閉連接,為0時關(guān)閉該功能
tcp-keepalive 300                       # tcp方式最大允許的連接數(shù)
daemonize no                            # 是否以守護進程方式運行
supervised no                           # 不使用監(jiān)控樹
pidfile /var/run/redis_6379.pid         # redis運行時保存pid的文件
loglevel verbose                        # 日志文件的記錄方式,默認為標(biāo)準(zhǔn)輸出
logfile /var/log/redis/redis.log        # redis日志文件的保存路徑
databases 16                            # 系統(tǒng)中保存redis數(shù)據(jù)庫的數(shù)量
save 900 1                              # redis中900秒之內(nèi)有1次更新操作時,把數(shù)據(jù)同步到文件中保存
save 300 10                             # redis在300秒內(nèi)有10次更新操作時,把數(shù)據(jù)同步到文件中保存
save 60 10000                           # redis在60秒內(nèi)有10000次更新操作時,把數(shù)據(jù)同步到文件中保存
stop-writes-on-bgsave-error yes
rdbcompression yes                      # redis中的數(shù)據(jù)保存到本地數(shù)據(jù)庫時是否啟動壓縮,默認為yes
rdbchecksum yes
dbfilename dump.rdb                     # 本地數(shù)據(jù)庫的文件名
dir /var/lib/redis                      # 本地數(shù)據(jù)庫的路徑
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly no                           # 是否在每次更新操作時進行日志記錄
appendfilename "appendonly.aof"         # 指定更新日志的文件名
appendfsync everysec                    # 每秒鐘把redis中的數(shù)據(jù)同步到本地文件一次
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60    #
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes

6.redis的交互式界面

[root@bogon ~]# redis-cli   # 進入redis的交互式界面
127.0.0.1:6379>

可以看到,已經(jīng)進入到redis的交互環(huán)境了

127.0.0.1:6379> set k1 v1   # 設(shè)定k1這個鍵的值為v1
OK
127.0.0.1:6379> get k1      # 獲取k1的值
"v1"    
127.0.0.1:6379> set k2 v2   # 設(shè)定k2的值為v2
OK
127.0.0.1:6379> get k2      # 獲取k2的值
"v2"

7.python3操作redis

在linux系統(tǒng)中打開redis的配置文件/etc/redis.conf

把第61行修改為

bind 0.0.0.0

表示所有的主機都可以連接

然后重啟redis,使配置文件生效

[root@bogon ~]# systemctl restart redis.service

在windows系統(tǒng)中,安裝redis模塊

pip3 install redis

新建redis_test.py文件,文件內(nèi)容為:

import redis
r1=redis.Redis(host="192.168.16.220",port=6379)
print("第一次讀取的k1值:",r1.get("k1"))
print("第一次讀取的k2值:",r1.get("k2"))
r1.set("k3","v3")
r1.delete("k1")
r1.delete("k2")
print("第二次獲取k1的值",r1.get("k1"))
print("第二次獲取k2的值",r1.get("k2"))
print(r1.get("k3"))

運行結(jié)果:

第一次讀取的k1值: b'v1'
第一次讀取的k2值: b'v2'
第二次獲取k1的值 None
第二次獲取k2的值 None
b'v3'

再次在linux的命令提示符下獲取k1和k2的值

127.0.0.1:6379> get k1
(nil)
127.0.0.1:6379> get k2
(nil)

因為k1和k2的值已經(jīng)在redis_test.py中被刪除了,所以獲取到的值為None.

8.使用Redis的好處

(1) 速度快,因為數(shù)據(jù)存在內(nèi)存中,類似于HashMap,HashMap的優(yōu)勢就是查找和操作的時間復(fù)雜度都是O(1)

(2) 支持豐富數(shù)據(jù)類型,支持string,list,set,sorted set,hash

(3) 支持事務(wù),操作都是原子性,所謂的原子性就是對數(shù)據(jù)的更改要么全部執(zhí)行,要么全部不執(zhí)行

(4) 豐富的特性:可用于緩存,消息,按key設(shè)置過期時間,過期后將會自動刪除

關(guān)于Python操作redis的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

新聞標(biāo)題:Python操作redis的方法
URL標(biāo)題:http://muchs.cn/article0/piseoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、小程序開發(fā)電子商務(wù)、建站公司企業(yè)網(wǎng)站制作、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化