
docker部署python程序清空redis數據
線上服務器沒有獨立的python環境,也沒有外網可以裝包,因此我們大都採用docker部署服務和腳本。
這樣好處是:
- 不同的應用之間環境和包不同,互相隔離
- 方便移植,上傳鏡像文件其他機器直接下載部署
清空redis數據需求
web api採用了redis作為緩存,默認緩存時間為1天(從發起請求開始),集群數據每天6天更新到mysql,考慮到如果是晚上發起的請求,凌晨6點後的api返回的數據依然是緩存數據沒有更新,因此採用這種方式去更新,在集群數據寫入mysql以後,執行此任務,清空redis裡的緩存數據保證數據為最新
依賴環境
python版本3.5.2(從docker下載python鏡像)
依賴包
redis==2.10.6
Click==7.0
Cython==0.29.2
項目目錄
|
RefreshRedis
├──
refresh
.
py
清空程序
├──
config
.
json
數據庫配置文件
├──
Dockerfile
創建
docker
鏡像文件(文件名不可變)
├──
requirements
.
txt
需要安裝的包
refresh.py 清空redis數據腳本
#coding:utf-8
import
os
,
json
,
redis
import
click
class
BwRedisHandler
(
object
):
def
__init__
(
self
,
redis_config
):
self
.
redis_config
=
redis_config
self
.
pool
=
redis
.
ConnectionPool
(**
self
.
redis_config
)
self
.
r
=
redis
.
StrictRedis
(
connection_pool
=
self
.
pool
)
def
delele
(
self
,
key
):
self
.
r
.
delete
(
key
)
return
True
@property
def
keys
(
self
,
delete_prefixion
=
'Cloud:get'
):
return
[
k
for
k
in
self
.
r
.
keys
()
if
k
.
startswith
(
delete_prefixion
)]
if
self
.
r
.
keys
()
else
[]
def
rm_keys
(
self
):
n
=
0
if
self
.
keys
:
for
key
in
self
.
keys
:
self
.
delele
(
key
)
n
+=
1
(
'成功刪除{}條數據\n{}'
.
format
(
n
,
','
.
join
(
self
.
keys
)))
@click
.
command
()
@click
.
option
(
'--mode'
,
help
=
'local/test/prd'
)
def
main
(
mode
):
BASE_DIR
=
os
.
path
.
dirname
(
os
.
path
.
abspath
(
__file__
))
CONFIG_FILE
=
os
.
path
.
join
(
BASE_DIR
,
'config.json'
)
with
open
(
CONFIG_FILE
,
'r'
,
encoding
=
'utf-8'
)
as
fr
:
config
=
json
.
load
(
fr
)
CONFIG
=
config
[
mode
]
redis
=
BwRedisHandler
(
CONFIG
[
'redis'
])
redis
.
rm_keys
()
if
__name__
==
'__main__'
:
main
()
Dockerfile
#依賴的鏡像
FROM python
:
3.5
.
2
#開發者信息
MAINTAINER chengxinyao
<
chengxinyao1991@163
.
com
>
#鏡像描述及版本號
LABEL
Description
=
"RefreshRedis"
Vendor
=
"Bwang"
Version
=
"0.0.1"
#拷貝文件
COPY
.
/
src
/
# 執行命令
RUN pip install
-
i https
:
//pypi.douban.com/simple -I wheel setuptools
RUN pip install
-
r
/
src
/
requirements
.
txt
-
i https
:
//pypi.douban.com/simple
#指定路徑
WORKDIR
/
src
/
#命令行
CMD
[
"python"
,
"/src/refresh.py"
,
"--mode"
,
"test"
]
依據Dockerfile創建本地鏡像
#需進入到Dockerfile所在目錄
## docker build -t 鏡像名(小寫):版本號 .(小數點是指定鏡像構建過程中的上下文環境的目錄)
docker build
-
t refreshredis
:
0.0
.
1
.
創建鏡像過程
Sending
build context to
Docker
daemon
6.656kB
Step
1
/
8
:
FROM python
:
3.5
.
2
--->
432d0c6d4d9a
Step
2
/
8
:
MAINTAINER chengxinyao
<
chengxinyao@baiwang
.
com
>
省略
Successfully
built
85b2bb03caf7
Successfully
tagged refreshredis
:
0.0
.
1
出現
Successfully
tagged
鏡像名:版本號
即成功
查看鏡像
docker images
屏幕顯示如下
REPOSITORY TAG IMAGE ID CREATED SIZE
refreshredis
0.0
.
1
自動生成的
image_id
你的創建時間
705MB
保存鏡像為壓縮文件 refreshredis.tar.gz
docker save refreshredis
:
0.0
.
1
|
gzip
>
refreshredis
.
tar
.
gz
上傳壓縮文件到服務器
scp refreshredis
.
tar
.
gz root@
服務器:目錄
登錄到服務器去下載鏡像
docker load
-
i refreshredis
.
tar
.
gz
服務器上查看鏡像
docker images
服務器上依據該鏡像執行python腳本清空redis
docker run
-
it
--
rm refreshredis
:
0.0
.
1
python
/
src
/
refresh
.
py
--
mode test
閱讀更多 猿修心 的文章