server.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package rpc
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "github.com/spf13/viper"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/health/grpc_health_v1"
  10. "passport/app/rpc/pb"
  11. "passport/consul"
  12. )
  13. func RegisterToConsul() {
  14. consul.RegitserService("127.0.0.1:8500", &consul.ConsulService{
  15. Name: "im_passport",
  16. Tag: []string{"im_passport"},
  17. IP: "127.0.0.1",
  18. Port: viper.GetInt("server.rpc_port"),
  19. })
  20. }
  21. //health
  22. type Server struct{}
  23. type HealthImpl struct{}
  24. // Check 实现健康检查接口,这里直接返回健康状态,这里也可以有更复杂的健康检查策略,比如根据服务器负载来返回
  25. func (h *HealthImpl) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
  26. fmt.Print("health checking\n")
  27. return &grpc_health_v1.HealthCheckResponse{
  28. Status: grpc_health_v1.HealthCheckResponse_SERVING,
  29. }, nil
  30. }
  31. func (h *HealthImpl) Watch(req *grpc_health_v1.HealthCheckRequest, w grpc_health_v1.Health_WatchServer) error {
  32. return nil
  33. }
  34. func StartGrpcServer() {
  35. lis, err := net.Listen("tcp", ":"+viper.GetString("server.rpc_port"))
  36. if err != nil {
  37. log.Fatalf("failed to listen: %v", err)
  38. }
  39. s := grpc.NewServer()
  40. passportpb.RegisterPassportServer(s, &Server{})
  41. grpc_health_v1.RegisterHealthServer(s, &HealthImpl{})
  42. RegisterToConsul()
  43. if err := s.Serve(lis); err != nil {
  44. log.Fatalf("failed to serve: %v", err)
  45. }
  46. }