main.go 2.2 KB

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