123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package rpc
- import (
- "context"
- "fmt"
- "log"
- "net"
- "github.com/spf13/viper"
- "google.golang.org/grpc"
- "google.golang.org/grpc/health/grpc_health_v1"
- "passport/app/rpc/pb"
- "passport/consul"
- )
- func RegisterToConsul() {
- consul.RegitserService("127.0.0.1:8500", &consul.ConsulService{
- Name: "im_passport",
- Tag: []string{"im_passport"},
- IP: "127.0.0.1",
- Port: viper.GetInt("server.rpc_port"),
- })
- }
- //health
- type Server struct{}
- type HealthImpl struct{}
- // Check 实现健康检查接口,这里直接返回健康状态,这里也可以有更复杂的健康检查策略,比如根据服务器负载来返回
- func (h *HealthImpl) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
- fmt.Print("health checking\n")
- return &grpc_health_v1.HealthCheckResponse{
- Status: grpc_health_v1.HealthCheckResponse_SERVING,
- }, nil
- }
- func (h *HealthImpl) Watch(req *grpc_health_v1.HealthCheckRequest, w grpc_health_v1.Health_WatchServer) error {
- return nil
- }
- func StartGrpcServer() {
- lis, err := net.Listen("tcp", ":"+viper.GetString("server.rpc_port"))
- if err != nil {
- log.Fatalf("failed to listen: %v", err)
- }
- s := grpc.NewServer()
- passportpb.RegisterPassportServer(s, &Server{})
- grpc_health_v1.RegisterHealthServer(s, &HealthImpl{})
- RegisterToConsul()
- if err := s.Serve(lis); err != nil {
- log.Fatalf("failed to serve: %v", err)
- }
- }
|