系统:Centos 6
Redis版本:3.2.1
一、安装python redis模块
上传redis-py-master.zip
rz redis-py-master.zip
解压
unzip redis-py-master.zip
安装
python setup.py install
python3 setup.py install
二、脚本
#!/usr/local/bin/python3
##引入模块
import redis,time,datetime
##定义日志路径
log = "/var/log/redis_test.log"
##自定义函数
def getRedis():
try:
conn = redis.Redis(host="127.0.0.1",port=6379,password='123456789',decode_responses=True,health_check_interval=1) ##decode_responses=True 查询redis中key值去除"b"字符 health_check_interval监控检查时间
time1=datetime.datetime.now()##获取当前时间
time2=(str(time1))##字符化时间变量
conn.set("A",time2)##是指key A 值为时间字符串
value=conn.get("A")##获取key值
result=("A|"+str(value)+"|"+time2)##拼接结果
with open(log,"a") as f:##打开日志文件
f.write(result+'\n')##换行写入日志
time.sleep(1)##等待1S
except Exception as e:##连接不上redis后,跳转到异常处理,打印日志
time1=str(datetime.datetime.now())
result=(time1+'|redis 链接失败,正在重连')
with open(log,"a") as f:
f.write(result+'\n')
else:##其他操作
return redis
while True:###死循环
getRedis()##调取函数
三、测试
chmod +x test.py
./test.py
查看日志输出:
tailf /var/log/redis_test.log
down掉redis,启动redis
查看日志