问题描述
我想让Golang语言Web服务器保持正常运行,无论是否发生错误。
如何继续运行它?
I want to keep my Golang language web server working regardless of an error happens or not.How to keep running it always?
推荐答案
我们必须从2个角度检查永远在线服务器:
We have to inspect an always-on server from 2 perspectives:
- 处理/容忍在服务请求期间发生的错误
- 重启服务器应用程序如果崩溃或获取杀死
首先,你不需要做任何特殊的事情。如果您的处理程序发生混乱,它将不会破坏整个服务器,http服务器将从中恢复。它只会停止提供该特定请求。当然,您可以创建自己的处理程序,调用其他处理程序并在恐慌时恢复并以智能方式处理它,但这不是必需的。
For the first, you don't have to do anything special. If your handler panics, it will not blow your whole server, the http server will recover from that. It will only stop serving that specific request. Of course you can create your own handler which calls other handlers and recovers on panic and handle it in an intelligent way, but this is not a requirement.
For第二,它并不真正与Go相关。例如,如果您使用的是Linux,只需将已编译的Go可执行文件作为服务进行安装/注册,并将其正确配置为在其退出或崩溃时重新启动。
For the second, it's not really Go related. For example if you're on linux, simply install / register your compiled Go executable as a service, properly configured to have it restarted should it exit or crash.
例如在Ubuntu中使用进行服务配置,以下最小服务描述符将满足您的愿望:
For example in Ubuntu which uses systemd for service configuration, the following minimal service descriptor would fulfill your wishes:
[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
,您可以启用并启动它:
Put the above text in a file e.g. /etc/systemd/system/myservice.service
, and you can enable and start it with:
sudo systemctl enable myservice.service
sudo systemctl start myservice.service
第一个命令将符号链接放到正确的文件夹中,以便在系统启动时自动启动它。第二个命令现在启动它。
The first command places a symlink to the proper folder to have it auto-started on system startup. The second command starts it right now.
要验证它是否正在运行,请键入:
To verify if it's running, type:
sudo systemctl status myservice.service
(你可以省略。service 扩展名。)
(You can omit the .service
extension in most cases.)
现在,只要您的应用崩溃,或者操作系统重新启动,您的应用就会自动启动/重新开始。
Now whenever your app crashes, or the OS gets restarted, your app will be automatically started / restarted.
systemd的进一步阅读和教程:
Further reading and tutorials for systemd:
这篇关于继续运行Go Server作为后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!