无论是否发生错误,我都想让我的 Golang 语言 Web 服务器正常工作。 如何让它一直运行?
最佳答案
我们必须从两个角度检查永远在线的服务器:
- 处理/容忍服务请求期间发生的错误
- 如果服务器应用程序崩溃或被杀死,请重新启动它
首先,您不需要做任何特别的事情。如果您的处理程序发生 panic ,它不会破坏您的整个服务器,http 服务器将从中恢复。它只会停止为该特定请求提供服务。当然,您可以创建自己的处理程序,它调用其他处理程序并在出现错误时恢复并以智能方式处理它,但这不是必需的。
这里要注意一件事:Go 应用程序在 main
goroutine 结束时结束(即:main()
函数返回)。因此,即使服务请求的 goroutines 受到保护,如果您的主 goroutine 将结束(例如
panic ),您的应用仍会退出。
第二,它与围棋无关。例如,如果你在 linux 上,只需安装/注册你编译的 Go 可执行文件作为服务,正确配置以在它退出或崩溃时重新启动它。
例如在 Ubuntu 中使用 systemd对于服务配置,以下最小服务描述符将满足您的愿望:
[Unit]
Description=My Always-on Service
[Service]
Restart=always
Type=simple
ExecStart=/path/to/your/app -some=params passed
[Install]
WantedBy=multi-user.target
将上面的文本放在一个文件中,例如/etc/systemd/system/myservice.service
,您可以启用并启动它:
sudo systemctl enable myservice.service
sudo systemctl start myservice.service
第一个命令放置一个指向正确文件夹的符号链接(symbolic link),使其在系统启动时自动启动。第二个命令立即启动它。
要验证它是否正在运行,请键入:
sudo systemctl status myservice.service
(在大多数情况下,您可以省略 .service
扩展名。)
现在,每当您的应用程序崩溃或操作系统重新启动时,您的应用程序将自动启动/重新启动。
systemd 的进一步阅读和教程:
How To Use Systemctl to Manage Systemd Services and Units
Systemd Essentials: Working with Services, Units, and the Journal
Convert "run at startup" script from upstart to systemd for Ubuntu 16
关于web-services - 继续运行 Go Server 作为后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43650183/