windows通過python指令碼重啟本地redis

鍋爐房劉大爺發表於2020-10-23

1.檢查redis server是否執行正常

def check_server():
    conn = redis.StrictRedis(
        host="127.0.0.1",
        port=6379,
        db=0,
        socket_timeout=5,           # 發出命令接收響應的時間不能超過此引數設定時間
        socket_connect_timeout=5    # 建立連線超時時間
    )
    flag = False
    try:
        res = conn.get('a')
        flag = True
    except Exception as e:
        # print('check_server error: %s' % e)
        print(traceback.format_exc())
    return flag

2.獲取redis server程式id

def get_server_pid():
    import psutil
    spid = 0
    for process in psutil.process_iter():
        # info = process.as_dict(attrs=['name', 'pid'])
        name = process.name()
        pid = process.pid
        if name == 'redis-server.exe':
            # print(pid, type(pid))
            spid = pid
            break
    return spid

3.關掉之前的程式

def do_kill(pid):
    cmd = 'taskkill /pid ' + str(pid) + ' /f'
    try:
        os.system(cmd)
    except Exception as e:
        print('do_kill error: %s, pid: %s' % (e, pid))

4.重啟redis server

def restart_redis_server():
    # 直接通過命令列啟動redis server,無法得到之前redis server的資料,所以採用這種方式重啟redis
    cmd = r'start C:\work\redis_server_restart.bat'
    # print(cmd)
    result = 10086
    try:
        result = os.system(cmd)
    except Exception as e:
        print('restart restart_redis_server: %s' % e)
    return result

對應的redis_server_restart.bat指令碼:

@echo off
title redis-server
::set ENV_HOME="D:\redis"
::D:
set ENV_HOME="C:\Users\Administrator\Desktop\redis"
C:
color 0a
cd %ENV_HOME%
redis-server.exe redis.windows.conf
::exit

 

相關文章