07987fd8ff7dea5cb374334967eb8973dd95021c.svn-base 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/longjoy/micro-go-course/section13/register/discovery"
  8. "github.com/longjoy/micro-go-course/section13/register/endpoint"
  9. service "github.com/longjoy/micro-go-course/section13/register/service"
  10. "github.com/longjoy/micro-go-course/section13/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. client := discovery.NewDiscoveryClient(*consulAddr, *consulPort)
  32. errChan := make(chan error)
  33. srv := service.NewRegisterServiceImpl(client)
  34. endpoints := endpoint.RegisterEndpoints{
  35. DiscoveryEndpoint: endpoint.MakeDiscoveryEndpoint(srv),
  36. HealthCheckEndpoint: endpoint.MakeHealthCheckEndpoint(srv),
  37. }
  38. handler := transport.MakeHttpHandler(context.Background(), &endpoints)
  39. go func() {
  40. errChan <- http.ListenAndServe(":" + strconv.Itoa(*servicePort), handler)
  41. }()
  42. go func() {
  43. // 监控系统信号,等待 ctrl + c 系统信号通知服务关闭
  44. c := make(chan os.Signal, 1)
  45. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  46. errChan <- fmt.Errorf("%s", <-c)
  47. }()
  48. instanceId := *serviceName + "-" + uuid.New().String()
  49. err := client.Register(context.Background(), *serviceName, instanceId, "/health", *serviceAddr, *servicePort, nil, nil)
  50. if err != nil{
  51. log.Printf("register service err : %s", err)
  52. os.Exit(-1)
  53. }
  54. err = <-errChan
  55. log.Printf("listen err : %s", err)
  56. client.Deregister(context.Background(), instanceId)
  57. }
  58. func init(){
  59. file := "./" +"register.log"
  60. logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  61. if err != nil {
  62. panic(err)
  63. }
  64. log.SetOutput(logFile) // 将文件设置为log输出的文件
  65. log.SetFlags(log.Ldate|log.Lshortfile)
  66. }