2022年06月23日 15:21:44

基于watchman实现golang项目热编译自动重启 Featured

作者: 

在使用golang开发项目的过程中,由于golang需要编译运行,因此每次内容变更后都需要停止服务、重新编译运行才能查看效果。
这样的流程,不仅降低了开发效率,也带来非常不友好的体验。
针对这样的痛点,我找到了一个比较好用的文件变更监听软件:watchman。
它可以监听项目文件变更,并通过定制trigger的方式,自动执行shell命令,这样就能实现我们需要的内容变更后自动重启服务的效果。
那么,watchman需要怎样使用才能监控项目变更自动重启服务呢?

安装

  1. # install for mac
  2. brew install watchman

使用

使用过程分两步:

1、监听项目目录

  1. # watchman watch-project /path/to/project
  2. watchman watch-project /www/watch-demo
  3. 示例返回:
  4. {
  5. "version": "2021.12.06.00",
  6. "watch": "/www/watch-demo",
  7. "watcher": "fsevents"
  8. }

2、注册触发器

2.1 编辑触发器配置内容 /www/watch-demo/watch-config.json

  1. [
  2. "trigger",
  3. "/www/watch-demo",
  4. {
  5. "name": "watch-demo",
  6. "expression":
  7. [
  8. "pcre",
  9. "\\.go$"
  10. ],
  11. "command":
  12. [
  13. "sh", "/www/watch-demo/restart.sh"
  14. ]
  15. }
  16. ]

2.2 编辑项目自动编译重启命令shell /www/watch-demo/restart.sh

  1. #!/bin/sh
  2. shell_name="watch-demo.run"
  3. #关闭旧进程
  4. if [ `ps aux | grep ${shell_name} | grep -v grep | awk '{print $2}'` ]; then
  5. ps aux | grep ${shell_name} | grep -v grep | awk '{print $2}' | xargs kill
  6. fi
  7. cd /www/watch-demo
  8. go build -o ${shell_name} ./main.go
  9. ./${shell_name} 2>&1 &
  10. rm -f ${shell_name}

2.3 注册触发器,内容变更自动编译重启

  1. watchman -j < /www/watch-demo/watch-config.json
  2. 示例返回:
  3. {
  4. "version": "2021.12.06.00",
  5. "triggerid": "watch-demo",
  6. "disposition": "created"
  7. }
  8. 可能报错:
  9. {
  10. "version": "2021.12.06.00",
  11. "error": "watchman::RootResolveError: RootResolveError: unable to resolve root /www/watch-demo: RootResolveError: directory /www/watch-demo is not watched"
  12. }
  13. 原因:未执行监听项目目录命令 watchman watch-project /www/watch-demo
  14. 解决:执行监听项目目录命令

至此,我们就添加好/www/watch-demo/项目目录下文件变更的自动编译重启监控,每次修改内容,watchman都会自动调用我们的restart.sh命令进行处理。

查看监控运行日志

  1. # ps aux| grep watchman 请查看--logfile关联的日志文件
  2. tail -f /opt/homebrew/var/run/watchman/macbok-state/log

查看监控列表

  1. watchman trigger-list /www/watch-demo
  2. 示例返回:
  3. {
  4. "version": "2021.12.06.00",
  5. "triggers": [
  6. {
  7. "command": [
  8. "sh",
  9. "/www/watch-demo/restart.sh"
  10. ],
  11. "expression": [
  12. "pcre",
  13. "\\.go$"
  14. ],
  15. "name": "watch-demo"
  16. }
  17. ]
  18. }

删除监控

  1. watchman trigger-del /www/watch-demo watch-demo
  2. 示例返回:
  3. {
  4. "version": "2021.12.06.00",
  5. "deleted": true,
  6. "trigger": "watch-demo"
  7. }

更多

watchman还有更多功能,感兴趣的朋友,点击下面项目地址去挖掘一下吧~ o_O

项目地址

https://facebook.github.io/watchman/

示例代码

watchman监听golang项目自动重启demo



未经同意禁止转载!
转载请附带本文原文地址:基于watchman实现golang项目热编译自动重启,首发自 Zjmainstay学习笔记
阅读( 1577 )
看完顺手点个赞呗:
(2 votes)

1.PHP cURL群:PHP cURL高级技术
2.正则表达式群:专精正则表达式
3. QQ联系(加请说明):QQ联系博主(951086941)
4. 邮箱:zjmainstay@163.com
5. 打赏博主:

网站总访问量: