main.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package main
  4. import (
  5. "context"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "net"
  10. "os"
  11. "os/signal"
  12. "syscall"
  13. "time"
  14. "smart-supplier-management/impl"
  15. "smart-supplier-management/parser"
  16. "github.com/jaryhe/gopkgs/database"
  17. "github.com/jaryhe/gopkgs/tasker"
  18. "google.golang.org/grpc"
  19. "smart-supplier-management/pb"
  20. )
  21. var (
  22. configFile = flag.String("config", "/etc/smart/common.yaml", "config file location")
  23. version = flag.Bool("version", false, "print the version")
  24. GitCommit = "library-import"
  25. Version = "library-import"
  26. )
  27. func showVersion() {
  28. fmt.Println("Version: ", Version)
  29. fmt.Println("GitCommit:", GitCommit)
  30. }
  31. func prepare(filename string) {
  32. // 加载配置
  33. err := parser.LoadConfig(filename)
  34. if err != nil {
  35. fmt.Printf("get conf failed, err: %+v\n\n", err)
  36. os.Exit(1)
  37. }
  38. // 注册处理函数
  39. // parser.Register(parser.MysqlHandler, parser.RedisHandler, parser.LoggerHandler)
  40. parser.Register(parser.LoggerHandler, parser.MysqlHandler, parser.InfluxdbHandler)
  41. // 执行注册的处理函数
  42. parser.Handle()
  43. }
  44. func run() {
  45. // 开始监听
  46. serveAddr := fmt.Sprintf("%s:%d", parser.Conf.Rpc.SmartSupplierManagement.ServiceIp, parser.Conf.Rpc.SmartSupplierManagement.ServicePort)
  47. log.Printf("Listening and serving TCP on %s\n", serveAddr)
  48. lis, err := net.Listen("tcp", serveAddr)
  49. if err != nil {
  50. os.Exit(1)
  51. }
  52. s := grpc.NewServer()
  53. impl.Register(s)
  54. go func() {
  55. if err := s.Serve(lis); err != nil {
  56. log.Fatalf("HTTP server listen failed. err: %s\n", err.Error())
  57. }
  58. }()
  59. conns := pb.SetupClients()
  60. for _, conn := range conns {
  61. defer conn.Close()
  62. }
  63. // 优雅关闭服务器
  64. sigChan := make(chan os.Signal, 1)
  65. // 捕获信号
  66. signal.Notify(sigChan, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
  67. sigValue := <-sigChan
  68. log.Printf("Got a signal:%v", sigValue)
  69. // 让tasker安全退出
  70. tasker.SignalNotify(sigValue)
  71. // 不管什么行为,都等待5秒退出
  72. log.Println("Start to shutdown server...")
  73. _, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  74. defer cancel()
  75. s.Stop()
  76. log.Println("Shutdown server finished.")
  77. }
  78. func main() {
  79. defer func() {
  80. database.Close()
  81. }()
  82. flag.Parse()
  83. if *version {
  84. showVersion()
  85. os.Exit(1)
  86. }
  87. prepare(*configFile)
  88. //go utils.Free()
  89. run()
  90. return
  91. }