package main import ( "context" "fmt" "github.com/go-redis/redis/v8" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" "google.golang.org/grpc/resolver/manual" "hilo-algoCenter/algo" "hilo-algoCenter/common/config" "hilo-algoCenter/common/mylogrus" "hilo-algoCenter/protocol/userCenter" "time" ) const ( default_redis_address = "47.244.34.27:6379" default_redis_password = "8QZ9JD1zLvPR3yHf" redis_section = 0 ) var kacp = keepalive.ClientParameters{ Time: 10 * time.Second, // send pings every 10 seconds if there is no activity Timeout: time.Second, // wait 1 second for ping ack before considering the connection dead PermitWithoutStream: true, // send pings even without active streams } func main() { // init redis rdb := redis.NewClient(&redis.Options{ Addr: config.GetConfigRedis().REDIS_HOST, Password: config.GetConfigRedis().REDIS_PASSWORD, DB: redis_section, }) result, err := rdb.Ping(context.Background()).Result() if err != nil { mylogrus.MyLog.Fatal(err) } else if result != "PONG" { mylogrus.MyLog.Fatalf("Invalid ping response %s", result) } // init redis cluster rdbCluster := redis.NewClient(&redis.Options{ Addr: config.GetConfigRedis().REDIS_CLUSTER_HOST, Password: config.GetConfigRedis().REDIS_CLUSTER_PASSWORD, }) redisKey := fmt.Sprintf("service:userCenter") ipPorts, err := rdbCluster.ZRangeByScore(context.Background(), redisKey, &redis.ZRangeBy{ Min: fmt.Sprintf("%d", time.Now().Add(-time.Second*15).Unix()), // 3倍心跳 Max: "+inf", }).Result() if err != nil { failMsg := fmt.Sprintf("get service fail,svc:%v,err:%v", "userCenter", err) mylogrus.MyLog.Errorf(failMsg) } else if len(ipPorts) > 0 { } if len(ipPorts) <= 0 { ipPorts = []string{"127.0.0.1:50040"} } addresses := make([]resolver.Address, len(ipPorts)) for i, s := range ipPorts { addresses[i].Addr = s mylogrus.MyLog.Infof("address : %s", s) } r := manual.NewBuilderWithScheme("hilo") r.InitialState(resolver.State{Addresses: addresses}) userCenterAddr := fmt.Sprintf("%s:///usercenter", r.Scheme()) // Set up addresses connection to the userCenter. conn, err := grpc.Dial(userCenterAddr, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithKeepaliveParams(kacp), grpc.WithResolvers(r), grpc.WithDefaultServiceConfig("{ \"loadBalancingPolicy\": \"round_robin\" }")) if err != nil { mylogrus.MyLog.Fatalf("did not connect: %v", err) } //defer conn.Close() userClient := userCenter.NewUserClient(conn) if userClient == nil { mylogrus.MyLog.Fatalln("userClient null") } algo.Start(userClient, rdb) select {} }