如何实现关闭命令窗口不关闭redis服务?
在 Windows 环境下,如果你希望 关闭命令窗口后 Redis 服务仍然运行,可以采用以下几种方法:
方法 1:将 Redis 安装为 Windows 服务(推荐)
步骤 1:安装 Redis 服务
在 管理员权限的 CMD/PowerShell 执行:
redis-server --service-install redis.windows.conf --loglevel verbose
redis.windows.conf
是你的 Redis 配置文件(确保路径正确)。--loglevel verbose
可选,用于设置日志级别。
步骤 2:启动 Redis 服务
redis-server --service-start
检查服务状态:
sc query Redis
停止服务:
redis-server --service-stop
卸载服务:
redis-server --service-uninstall
✅ 优点:关闭 CMD 窗口后 Redis 仍会运行,适合长期使用。
❌ 缺点:需要管理员权限。
方法 2:使用 start /B
后台运行
如果不想安装服务,可以临时后台运行:
start /B redis-server.exe redis.windows.conf
/B
表示不创建新窗口,后台运行。- 关闭时需手动
taskkill
:taskkill /F /IM redis-server.exe
✅ 优点:简单快捷,不需要管理员权限。
❌ 缺点:关闭 CMD 后 Redis 仍然会关闭(不推荐长期使用)。
方法 3:使用 nssm
(非官方服务管理器)
如果 Redis 自带的 --service-install
不稳定,可以用 nssm
管理:
- 下载 nssm
- 安装 Redis 服务:
nssm install Redis
- 在 GUI 界面设置:
- Path:
C:\redis\redis-server.exe
- Startup directory:
C:\redis\
- Arguments:
redis.windows.conf
- Path:
- 启动服务:
nssm start Redis
✅ 优点:稳定,适合生产环境。
❌ 缺点:需要额外安装 nssm
。
方法 4:使用 PowerShell 后台任务
Start-Process -NoNewWindow -FilePath "redis-server.exe" -ArgumentList "redis.windows.conf"
-NoNewWindow
表示后台运行。- 关闭方式:
Get-Process redis-server | Stop-Process
✅ 优点:适合脚本化管理。
❌ 缺点:关闭 PowerShell 后 Redis 仍然会关闭(不推荐长期使用)。
方法 5:使用 winsw
(Windows Service Wrapper)
- 下载 winsw
- 创建
RedisService.xml
:<service> <id>Redis</id> <name>Redis Server</name> <description>Redis Cache Server</description> <executable>C:\redis\redis-server.exe</executable> <arguments>redis.windows.conf</arguments> <log mode="roll"></log> </service>
- 安装并启动服务:
winsw install RedisService.xml winsw start RedisService.xml
✅ 优点:稳定,适合企业级部署。
❌ 缺点:配置稍复杂。
总结
方法 | 适用场景 | 关闭 CMD 后是否存活 | 是否需要管理员权限 |
---|---|---|---|
--service-install |
长期运行(推荐) | ✅ 是 | ✅ 需要 |
start /B |
临时测试 | ❌ 否 | ❌ 不需要 |
nssm |
稳定服务管理 | ✅ 是 | ✅ 需要 |
PowerShell | 脚本化运行 | ❌ 否 | ❌ 不需要 |
winsw |
企业级部署 | ✅ 是 | ✅ 需要 |
最佳实践
- 推荐方法 1(
--service-install
),适合大多数场景。 - 如果 Redis 官方服务安装失败,可以用 方法 3(
nssm
) 或 方法 5(winsw
)。 - 如果只是临时测试,可以用 方法 2(
start /B
) 或 方法 4(PowerShell)。
这样,即使关闭 CMD/PowerShell 窗口,Redis 仍然会继续运行!🚀