8283c04c17a04da649ea1dd48cacac25cf813d79.svn-base 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/longjoy/micro-go-course/section28/goods/endpoint"
  8. "github.com/longjoy/micro-go-course/section28/goods/pkg/discovery"
  9. "github.com/longjoy/micro-go-course/section28/goods/pkg/loadbalancer"
  10. "github.com/longjoy/micro-go-course/section28/goods/service"
  11. "github.com/longjoy/micro-go-course/section28/goods/transport"
  12. "golang.org/x/time/rate"
  13. "log"
  14. "net/http"
  15. "os"
  16. "os/signal"
  17. "strconv"
  18. "syscall"
  19. )
  20. func main() {
  21. consulAddr := flag.String("consul.addr", "localhost", "consul address")
  22. consulPort := flag.Int("consul.port", 8500, "consul port")
  23. servicePort := flag.Int("service.port", 12313, "service port")
  24. serviceName := flag.String("service.name", "good", "service name")
  25. serviceAddr := flag.String("service.addr", "localhost", "service addr")
  26. flag.Parse()
  27. flag.Parse()
  28. errChan := make(chan error)
  29. client := discovery.NewDiscoveryClient(*consulAddr, *consulPort)
  30. instanceId := *serviceName + "-" + uuid.New().String()
  31. err := client.Register(context.Background(), *serviceName, instanceId, "/health", *serviceAddr, *servicePort, nil, nil)
  32. loadbalancer := loadbalancer.NewRandomLoadBalancer()
  33. srv := service.NewGoodsServiceImpl(client, loadbalancer)
  34. limiter := rate.NewLimiter(20, 20)
  35. endpoints := endpoint.GoodsEndpoints{
  36. GoodsDetailEndpoint: endpoint.MakeGoodsDetailEndpoint(srv, limiter),
  37. HealthCheckEndpoint: endpoint.MakeHealthCheckEndpoint(srv),
  38. }
  39. handler := transport.MakeHttpHandler(context.Background(), &endpoints)
  40. go func() {
  41. errChan <- http.ListenAndServe(":"+strconv.Itoa(*servicePort), handler)
  42. }()
  43. go func() {
  44. // 监控系统信号,等待 ctrl + c 系统信号通知服务关闭
  45. c := make(chan os.Signal, 1)
  46. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  47. errChan <- fmt.Errorf("%s", <-c)
  48. }()
  49. err = <-errChan
  50. log.Printf("listen err : %s", err)
  51. client.Deregister(context.Background(), instanceId)
  52. }