e001300a1fa82b8df47028de53d11bcd1060648c.svn-base 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/longjoy/micro-go-course/section14/register/discovery"
  8. "github.com/longjoy/micro-go-course/section14/register/endpoint"
  9. service "github.com/longjoy/micro-go-course/section14/register/service"
  10. "github.com/longjoy/micro-go-course/section14/register/transport"
  11. "log"
  12. "net/http"
  13. "os"
  14. "os/signal"
  15. "strconv"
  16. "syscall"
  17. )
  18. /**
  19. * @Author : dixuanhuang
  20. * @File : main.go
  21. * @Date : 2020/8/10 9:19 下午
  22. * @Description:
  23. **/
  24. func main() {
  25. consulAddr := flag.String("consul.addr", "localhost", "consul address")
  26. consulPort := flag.Int("consul.port", 8500, "consul port")
  27. serviceName := flag.String("service.name", "register", "service name")
  28. serviceAddr := flag.String("service.addr", "localhost", "service addr")
  29. servicePort := flag.Int("service.port", 12312, "service port")
  30. flag.Parse()
  31. instanceId := *serviceName + "-" + uuid.New().String()
  32. client, err := discovery.NewDiscoveryClient(*consulAddr, *consulPort, discovery.NewAgentServiceRegistration(
  33. *serviceName, instanceId, "/health", *serviceAddr, *servicePort, nil))
  34. if err != nil{
  35. log.Printf("register service err : %s", err)
  36. os.Exit(-1)
  37. }
  38. errChan := make(chan error)
  39. srv := service.NewRegisterServiceImpl(client)
  40. endpoints := endpoint.RegisterEndpoints{
  41. DiscoveryEndpoint: endpoint.MakeDiscoveryEndpoint(srv),
  42. HealthCheckEndpoint: endpoint.MakeHealthCheckEndpoint(srv),
  43. }
  44. handler := transport.MakeHttpHandler(context.Background(), &endpoints)
  45. go func() {
  46. errChan <- http.ListenAndServe(":" + strconv.Itoa(*servicePort), handler)
  47. }()
  48. go func() {
  49. // 监控系统信号,等待 ctrl + c 系统信号通知服务关闭
  50. c := make(chan os.Signal, 1)
  51. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  52. errChan <- fmt.Errorf("%s", <-c)
  53. }()
  54. client.Register(context.Background())
  55. err = <-errChan
  56. log.Printf("listen err : %s", err)
  57. client.Deregister(context.Background())
  58. }
  59. func init(){
  60. file := "./" +"register.log"
  61. logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  62. if err != nil {
  63. panic(err)
  64. }
  65. log.SetOutput(logFile) // 将文件设置为log输出的文件
  66. log.SetFlags(log.Ldate|log.Lshortfile)
  67. }