在实际开发过程中,有时候会遇到如何编写Go开机自启服务的需求,在linux中我们可以使用systemd
来进行托管,windows下可以通过注册表
来实现,mac下可以通过launchd
来实现,上面的方式对于开发者来说,并不是什么困难的事情,但是对于使用者而言,是并不希望通过这么复杂的方式来达到开机自启的功能的。这个时候,作为开发者,就需要使用其他的方式来实现开机自启的功能,下面讲一个Go中,借助这个库 github.com/kardianos/service 来简化如何实现开机自启功能。
我们先来看一看 github.com/kardianos/service 上面的自我介绍:Run go programs as a service on major platforms.
(资料图片)
如何理解上面这句话呢,上面这句话翻译出来的意思是:"在主要平台上将Go程序作为服务运行"。
这意味着我们可以将Go编写的程序以服务的形式在主要操作系统上运行,例如Windows、Linux、macOS等。这意味着程序可以在后台持续运行,而不需要用户手动启动或停止它们。这种方式可以提高程序的可靠性和稳定性,同时也方便了程序的管理和监控。
那该如何理解服务
呢?
服务(Service)是指在计算机系统中,为用户或其他程序提供某种功能的程序或进程。服务通常在后台运行,可以长时间运行,不需要用户交互,可以自动启动和停止。服务可以提供各种功能,如网络服务、数据库服务、文件共享服务等。在操作系统中,服务通常以服务进程的形式运行,可以通过系统管理工具进行管理和配置。
有了上面的了解过后,再来看看官方自己的描述。service will install / un-install, start / stop, and run a program as a service (daemon). Currently supports Windows XP+, Linux/(systemd | Upstart | SysV), and OSX/Launchd.
如何理解上面这句话呢,我说说自己的理解。
我们可以将编写好的代码打包成二进制文件后,通过
二进制文件名 + install / un-install, start / stop
来运行我们的服务,程序将作为服务(守护进程)运行。目前支持Windows XP+、Linux/(systemd|Upstart|SysV)和OSX/Launchd。
Windows controls services by setting up callbacks that is non-trivial. This is very different then other systems. This package provides the same API despite the substantial differences. It also can be used to detect how a program is called, from an interactive terminal or from a service manager.
下面是我的理解:
1.2 kardianos/service 安装Windows 通过设置回调来控制服务,这与其他系统非常不同。这个包提供了相同的API,尽管存在很大差异。它还可以用于检测程序是从交互式终端还是从服务管理器调用的。
看到这里的时候,我其他不太理解最后一句话,什么叫从
服务管理器
调用。将在 2.2 章节中介绍。
安装 github.com/kardianos/service 的方式和其他方式一样。
go get github.com/kardianos/service指定版本方式go get github.com/kardianos/service@v1.2.2
2、kardianos/service 使用方式2.1 kardianos/service 简单的使用以下介绍都是基于 github.com/kardianos/service@v1.2.2 进行讲解的。
我们先来看一个简单的例子,代码如下:
package mainimport ("fmt""github.com/kardianos/service""os")type SystemService struct {}func (ss *SystemService) Start(s service.Service) error {fmt.Println("coming Start.......")go ss.run()return nil}func (ss *SystemService) run() {fmt.Println("coming run.......")}func (ss *SystemService) Stop(s service.Service) error {fmt.Println("coming Stop.......")return nil}func main() {fmt.Println("service.Interactive()---->", service.Interactive())svcConfig := &service.Config{Name: "custom-service",DisplayName: "custom service",Description: "this is github.com/kardianos/service test case",}ss := &SystemService{}s, err := service.New(ss, svcConfig)if err != nil {fmt.Printf("service New failed, err: %v\n", err)os.Exit(1)}if len(os.Args) > 1 {err = service.Control(s, os.Args[1])if err != nil {fmt.Printf("service Control 111 failed, err: %v\n", err)os.Exit(1)} return}// 默认 运行 Runerr = s.Run()if err != nil {fmt.Printf("service Control 222 failed, err: %v\n", err)os.Exit(1)}}
通过go run main.go
得到如下结果,注意:程序并不会终止,而是阻塞住了
。
service.Interactive()----> truecoming Start.......coming run.......
实际上,kardianos/service
为我们提供了下面的参数使用,我们可以通过go build -o main main.go
编译得到二进制文件,然后使用下面的命令来运行服务。
# 生成开机自启服务所需要的文件,文件位置根据操作系统的不同而不用,linux在 /etc/systemd/system 或者 /lib/systemd/system 下./main install# 删除上面生成的文件./main uninstall# 开启服务./main start# 重启服务./main restart# 停止服务./main stop
2.2 kardianos/service 如何做开机自启服务接下来以 Linux 为例,进行讲解。其他系统大家可自行尝试。
具体的步骤如下:
1、第一步是编写代码,编写完成后,编译成二进制文件。
代码就以 2.1 中的为例。首先编译成二进制文件。
go build -o main main.go
2、运行 可执行文件。
# 这将在 /etc/systemd/system 或者 /lib/systemd/system 中生成 custom-service.service 文件# 我这里测试的时候是在 /etc/systemd/system 中生成的./main install
看到这里,用过systemd的朋友应该可以猜到 kardianos/service 背后是通过什么来实现开机自启的。就是通过
systemd
来管理的。
3、将 custom-service.service 服务设置为开机自启.
运行下面命令将我们编写的程序设置为开机自启服务。
# 设置服务开机自启动systemctl enable test-service.service# 启动systemctl start test-service.service
下面是systemctl
常用的命令。
# 启动systemctl start test-service.service# 停止systemctl stop test-service.service# 设置服务开机自启动systemctl enable test-service.service# 查询是否自启动服务 systemctl is-enabled test-service.service# 取消服务器开机自启动 systemctl disable test-service.service# 列出正在运行的服务systemctl list-units --type=service
接下来我们看看服务管理器是什么意思?1、./main install
2、查看custom-service.service
文件
3、执行systemctl start custom-service.service
后,查看服务运行过程
2.3 结合 cli 使用这里就是上面
服务管理器
的作用,也就是说,如何服务是手动运行的,那么service.Interactive()
返回 true,比如:./main start。如何是系统管理器运行的,则返回 false,比如:systemctl start custom-service.service。
通过上面的例子,我们大概知道了如何使用 github.com/kardianos/service 。实际使用中,一般的服务都可以通过-h
来查看帮助文档,但是我们我们通过./main -h
会报错,所以需要完善下代码,使我们的程序更容易使用。下面,我们一起看看,借助 github.com/urfave/cli/v2 来完成上面的需求。
package mainimport ("fmt""github.com/kardianos/service""github.com/urfave/cli/v2""os")type SystemService struct {}func (ss *SystemService) Start(s service.Service) error {fmt.Println("coming Start.......")go ss.run()return nil}func (ss *SystemService) run() {fmt.Println("coming run.......")}func (ss *SystemService) Stop(s service.Service) error {fmt.Println("coming Stop.......")return nil}func main() {app := cli.NewApp()app.Name = "custom-service"app.Usage = "how to use custom service"app.Commands = []*cli.Command{{Name: "install",Action: ctrlAction,},{Name: "uninstall",Action: ctrlAction,},{Name: "start",Action: ctrlAction,},{Name: "restart",Action: ctrlAction,},{Name: "stop",Action: ctrlAction,},}app.Flags = []cli.Flag{&cli.StringFlag{Name: "install",Value: "install",Usage: "Write the files required for startup",},&cli.StringFlag{Name: "uninstall",Value: "uninstall",Usage: "Delete startup files",},&cli.StringFlag{Name: "start",Value: "start",Usage: "start the service",},&cli.StringFlag{Name: "stop",Value: "stop",Usage: "stop the service",},&cli.StringFlag{Name: "restart",Value: "restart",Usage: "restart the service",},}app.Action = startActionapp.Run(os.Args)}func createSystemService() (service.Service, error) { fmt.Println("service.Interactive()---->", service.Interactive())svcConfig := &service.Config{Name: "custom-service",DisplayName: "custom service",Description: "this is github.com/kardianos/service test case",}ss := &SystemService{}s, err := service.New(ss, svcConfig)if err != nil {return nil, fmt.Errorf("service New failed, err: %v\n", err)}return s, nil}func ctrlAction(c *cli.Context) error {s, err := createSystemService()if err != nil {fmt.Printf("createSystemService failed, err: %v\n", err)return err}err = service.Control(s, c.Command.Name)if err != nil {fmt.Printf("service Run 222 failed, err: %v\n", err)return err}return nil}func startAction(c *cli.Context) error {s, err := createSystemService()if err != nil {fmt.Printf("createSystemService failed, err: %v\n", err)return err}// 默认 运行 Runerr = s.Run()if err != nil {fmt.Printf("service Run failed, err: %v\n", err)return err}return nil}
大家可以根据自己的需求进行开发,这里只是讲一个简单的案例而已。
编译:
go build -o main main.go
运行:
./main -hNAME: custom-service - how to use custom serviceUSAGE: custom-service [global options] command [command options] [arguments...]COMMANDS: install uninstall start restart stop help, h Shows a list of commands or help for one commandGLOBAL OPTIONS: --install value Write the files required for startup (default: "install") --uninstall value Delete startup files (default: "uninstall") --start value start the service (default: "start") --stop value stop the service (default: "stop") --restart value restart the service (default: "restart") --help, -h show help
上一篇:动态焦点:2023年5月2日山东省苯胺价格最新行情预测
下一篇:最后一页
- 今日热闻!浅谈如何使用 github.com/kardianos/service
- 动态焦点:2023年5月2日山东省苯胺价格最新行情预测
- 暴雪申请新专利:AI生成特定风格美术素材-全球视讯
- 今日关注:中直股份(600038):一季度业绩增长24%符合预期 直升机龙头业绩有望修复
- “广场建起来,锻炼唠嗑有了好去处”(帮扶县驻村手记)
- 全球观察:南京就业环境怎么样前景这个城市
- 美媒:美国第一共和银行股票或被移出标普指数_环球新动态
- “最拥挤”五一档票房飘红,《长空之王》《人生路不熟》最受欢迎 世界简讯
- 焦点速读:珩磨机_关于珩磨机介绍
- t型梁架施工全过程_T型梁_全球微资讯
- 微头条丨立夏将至,吃饺子就馋这种馅,清肝泻火,消炎又润肠,错过太可惜
- 五一去哪儿买丨购物进行中,当然选这里!_环球微资讯
- 外媒:曼城将与球队后卫阿克、里科-刘易斯进行续约_关注
- 陕西省首届中老年电视才艺大赛启动仪式成功举行
- 天天微资讯!口口卡盟是什么_口口卡盟
-
今日热闻!浅谈如何使用 github.com/kardianos/service
在实际开发过程中,有时候会遇到如何编写Go开机自启服务的需求,在linux中我们可以使用systemd来进行托管,
-
全球球精选!小长假叠加购物节 虹口警方一点一方案坚守平安
为了保证市民游客逛街购物的时候安全又舒心,虹口公安针对辖区各大商圈的特点,一点一方案,落实警力,做好
-
动态焦点:2023年5月2日山东省苯胺价格最新行情预测
中国报告大厅2023年5月2日山东省苯胺价格最新走势监测显示:山东义众鑫新材料有限公司报价机构,今日苯胺(
-
【环球新要闻】2023年5月2日山东省DMF价格最新行情预测
中国报告大厅2023年5月2日山东省DMF价格最新走势监测显示:山东义众鑫新材料有限公司报价机构,今日DMF(99 90
-
暴雪申请新专利:AI生成特定风格美术素材-全球视讯
据gamerant消息,暴雪的一项新专利介绍了一个用AI来生成特定风格美术素材的系统。这个新专利中描述的技术将
-
真狠啊!CMA禁止微软10年收购动视暴雪!Steam仅2块4《饥荒》焕发第二春!
真狠啊!CMA禁止微软在未来10年内收购动视暴雪据报道,在英国CMA阻止微软收购动视暴雪之后,微软所面临的困
-
今日关注:中直股份(600038):一季度业绩增长24%符合预期 直升机龙头业绩有望修复
中直股份(600038):一季度业绩增长24%符合预期直升机龙头业绩有望修复
-
九洲药业(603456):全面布局 跨越向上
九洲药业(603456):全面布局跨越向上
-
“广场建起来,锻炼唠嗑有了好去处”(帮扶县驻村手记)
忙完春耕,村民们的生活节奏慢了许多。傍晚时分,河北省滦平县北山根村广场上人头攒动,处处欢声笑语。象棋
-
研学旅行指导师助力学生成长—— 打造旅行课堂 带来别样体验(经济新方位·新职业新活力)-每日简讯
“大家知道‘天街小雨润如酥’的‘天街’是长安城的哪条街吗?”“为什么购物叫‘买东西’,在唐朝‘买...
-
全球观察:南京就业环境怎么样前景这个城市
1、南京就业环境怎么样基本上是分高中低三个级别,然后职称刚进来时每年升一级,后面就要考各种职称来提升
-
看点:北大研究生就业怎么样法学院前景计算机去向
1、北大研究生就业怎么样去向:(1)公务员。毕业生可在国家、省、市等行政管理部门从事管理或文字性工作,
-
美媒:美国第一共和银行股票或被移出标普指数_环球新动态
证券时报网讯,央视新闻消息,5月1日,美国第一共和银行盘前停牌。据美国有线电视新闻网报道,由于市值不能
-
国际货币基金组织总裁:未来全球银行业可能会暴露更多弱点-天天热门
证券时报网讯,央视新闻消息,当地时间5月1日,国际货币基金组织总裁格奥尔基耶娃在摩根大通收购美国第一共
-
“最拥挤”五一档票房飘红,《长空之王》《人生路不熟》最受欢迎 世界简讯
北京日报客户端|记者袁云儿程功2023年“五一”小长假,不仅市民出行旅游热情高涨,电影市场也迎来最拥挤...
-
世界热推荐:2023中央美院毕业季正式启幕,校门外看展观众排起长队
北京日报客户端|记者王广燕“嚯,这么壮观!”5月1日,中央美术学院北门排起了数百米长的队伍,引起了观...
-
焦点速读:珩磨机_关于珩磨机介绍
珩磨机,关于珩磨机介绍这个很多人还不知道,我们一起来看看!1、利用珩磨头珩磨工件精加工表面的磨床。2、
-
环球短讯!珩厝社区_关于珩厝社区介绍
珩厝社区,关于珩厝社区介绍这个很多人还不知道,我们一起来看看!1、珩厝社区,福建省厦门市翔安区香山街道
-
t型梁架施工全过程_T型梁_全球微资讯
1、T形截面梁的梁的中间部分称为梁肋,也叫做腹板。2、腹板主要作用上承受垂直荷载作用和保证稳定性的作用
-
在尝试中成长作文800字初中优秀作文_在尝试中成长作文
1、每个人的一生,都需要做许许多多的尝试;在成长的道路上,尝试是人生中的必修课。2、比如,尝试着举手发
-
微头条丨立夏将至,吃饺子就馋这种馅,清肝泻火,消炎又润肠,错过太可惜
大家好,我是小世。时间转眼进入5月份,5月6号就是立夏,意味着春天结束,开始进入夏天。在立夏这天,人们
-
世界简讯:其实,黑丝可以穿得很高级!
圣罗兰的创意总监AnthonyVaccarello曾说过:时装的意义就是要解放欲望。在现代很多女性的眼中,其实都特别
-
五一去哪儿买丨购物进行中,当然选这里!_环球微资讯
在老太原人的记忆里,说到购物,就不能不提到位于朝阳街的服装城。儿时每逢节假日,父母带着自己来服装城添
-
岳阳东站捡“万元包” 接力寻人完璧归赵|每日看点
湖南日报•新湖南客户端5月1日讯(记者徐典波通讯员刘映晖)“G9610次车上发现旅客遗失物品,请车站值班员
-
外媒:曼城将与球队后卫阿克、里科-刘易斯进行续约_关注
阿联酋媒体TheNational(国家报)消息,曼城将与球队后卫阿克、里斯-刘易斯两人续约。该媒体表示,阿克通过
广告
X 关闭
2月15日,为期40天的春运圆满收官。作为全国首个米字形高铁枢纽,今年春运以来郑州东站客流持续保持高位...
广告
X 关闭
- 1全球球精选!小长假叠加购物节 虹口警方一点一方案坚守平安
- 2【环球新要闻】2023年5月2日山东省DMF价格最新行情预测
- 3真狠啊!CMA禁止微软10年收购动视暴雪!Steam仅2块4《饥荒》焕发第二春!
- 4九洲药业(603456):全面布局 跨越向上
- 5研学旅行指导师助力学生成长—— 打造旅行课堂 带来别样体验(经济新方位·新职业新活力)-每日简讯
- 6看点:北大研究生就业怎么样法学院前景计算机去向
- 7国际货币基金组织总裁:未来全球银行业可能会暴露更多弱点-天天热门
- 8世界热推荐:2023中央美院毕业季正式启幕,校门外看展观众排起长队
- 9环球短讯!珩厝社区_关于珩厝社区介绍
- 10在尝试中成长作文800字初中优秀作文_在尝试中成长作文
5G在城市中的广泛应用,不仅提升了城市治理水平,为城市发展提档加速,也给人们的生活带来巨大变化。2月...