user_center.go 5.13 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9
package rpc

import (
	"context"
	"fmt"
	"git.hilo.cn/hilo-common/mylogrus"
	"git.hilo.cn/hilo-common/protocol/userCenter"
	"git.hilo.cn/hilo-common/resource/config"
	"git.hilo.cn/hilo-common/resource/consul"
hujiebin's avatar
hujiebin committed
10
	"git.hilo.cn/hilo-common/sdk/dingding"
hujiebin's avatar
hujiebin committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	consulapi "github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/resolver"
	"time"
)

const (
	Port = 50060
)

var userClient userCenter.UserClient
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
}

var (
	defaultUserCenterAddr = "127.0.0.1:50040" // userCenter default addr
	userCenterAddr        = defaultUserCenterAddr
	userCenterConsulName  = "userCenter"
)

// grpc服务发现
type Builder struct {
	addrs map[string][]string

	cc resolver.ClientConn
}

func (b *Builder) Scheme() string {
	return "uc" // userCenter
}

type Resolver struct {
}

func (r Resolver) ResolveNow(options resolver.ResolveNowOptions) {}

func (r Resolver) Close() {}

func (b *Builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
	r := &Resolver{}
	paths := b.addrs[target.URL.Path]
	addrs := make([]resolver.Address, len(paths))
	for i, s := range paths {
		addrs[i] = resolver.Address{Addr: s}
	}
	cc.UpdateState(resolver.State{Addresses: addrs})
	b.cc = cc
	return r, nil
}

func (b *Builder) UpdateState(addrs []string) {
	as := make([]resolver.Address, len(addrs))
	for i, s := range addrs {
		as[i] = resolver.Address{Addr: s}
	}
hujiebin's avatar
hujiebin committed
70 71 72
	if b.cc != nil {
		_ = b.cc.UpdateState(resolver.State{Addresses: as})
	}
hujiebin's avatar
hujiebin committed
73 74 75 76 77 78 79 80
}

func init() {
	// 本地环境下不需要userCenter
	if config.AppIsLocal() {
		mylogrus.MyLog.Infoln("userCenter is not required in local env.")
		return
	}
81 82
	client, err := consulapi.NewClient(consulapi.DefaultConfig()) //非默认情况下需要设置实际的参数
	if err != nil || client == nil {
hujiebin's avatar
hujiebin committed
83
		dingding.SendDingRobot(dingding.ROBOTWEBHOOK, fmt.Sprintf("consul client fail:%v", err), true)
84 85
		mylogrus.MyLog.Errorf("consul client fail:%v-%v", err, client)
	}
hujiebin's avatar
hujiebin committed
86 87
	// 服务发现
	bd := &Builder{addrs: map[string][]string{"/api": {userCenterAddr}}}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
	if client != nil {
		cataLog := client.Catalog()
		if cataLog != nil {
			services, _, err := cataLog.Service("userCenter", "", nil)
			if err != nil {
				mylogrus.MyLog.Errorf("cataLog.Service:err%v", err)
			}
			if len(services) == 0 {
				mylogrus.MyLog.Errorf("userCenter not found.")
			}
			var addrs []string
			for _, s := range services {
				addrs = append(addrs, fmt.Sprintf("%s:%d", s.ServiceAddress, s.ServicePort))
			}
			if len(addrs) > 0 {
				bd = &Builder{addrs: map[string][]string{"/api": addrs}}
				userCenterAddr = "uc:///api"
			}
			mylogrus.MyLog.Infof("userCenterAddr:%v,addr:%v", userCenterAddr, addrs)
		}
108 109 110 111
	}
	mylogrus.MyLog.Infof("connect userCenterAddr:%v", userCenterAddr)
	resolver.Register(bd)
	go func() {
hujiebin's avatar
hujiebin committed
112 113 114
		consul.RegisterWatcher(userCenterConsulName, func(addr []string) {
			if len(addr) > 0 {
				bd.UpdateState(addr) // 更新新的注册名
hujiebin's avatar
hujiebin committed
115
			}
hujiebin's avatar
hujiebin committed
116
		})
117
	}()
hujiebin's avatar
hujiebin committed
118 119 120 121 122 123 124 125

	//userCenterAddr := services[0].Address + ":" + strconv.Itoa(services[0].ServicePort)
	//mylogrus.MyLog.Printf("Choose userCenter %s, %s, weights: %v\n", services[0].ID, userCenterAddr, services[0].ServiceWeights)

	// Set up a connection to the userCenter.
	conn, err := grpc.Dial(userCenterAddr, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithKeepaliveParams(kacp),
		grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy":"%s"}`, "round_robin")))
	if err != nil {
hujiebin's avatar
hujiebin committed
126
		msg := fmt.Sprintf("mode:%v,连接userCenter失败:%v", config.GetMode(), err)
hujiebin's avatar
hujiebin committed
127 128
		dingding.SendDingRobot(dingding.ROBOTWEBHOOK, msg, true)
		mylogrus.MyLog.Fatalf(msg)
hujiebin's avatar
hujiebin committed
129 130 131 132
	}
	//defer conn.Close()
	userClient = userCenter.NewUserClient(conn)
	if userClient == nil {
hujiebin's avatar
hujiebin committed
133
		msg := fmt.Sprintf("mode:%v,userClient null", config.GetMode())
hujiebin's avatar
hujiebin committed
134 135
		dingding.SendDingRobot(dingding.ROBOTWEBHOOK, msg, true)
		mylogrus.MyLog.Fatalln(msg)
hujiebin's avatar
hujiebin committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	}
}

func multicast(uids []uint64, msgType uint32, data []byte) ([]uint64, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	rsp, err := userClient.Multicast(ctx, &userCenter.MulticastMessage{
		Uids:    uids,
		MsgType: msgType,
		PayLoad: data,
	})
	if err != nil {
		mylogrus.MyLog.Errorf("Multicast message failed %s", err.Error())
	}
	if rsp != nil {
		mylogrus.MyLog.Infof("Multicast message res:%+v", rsp)
		return rsp.FailedUids, err
	} else {
		return []uint64{}, err
	}
}

//广播
func broadcast(msgType uint32, data []byte) ([]uint64, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	rsp, err := userClient.Broadcast(ctx, &userCenter.BroadcastMessage{
		MsgType: msgType,
		PayLoad: data,
	})
	if err != nil {
		mylogrus.MyLog.Errorf("broadcast message failed %s", err.Error())
	}
	if rsp != nil {
		mylogrus.MyLog.Infof("broadcast message res:%v", rsp)
		return rsp.FailedUids, err
	} else {
		return []uint64{}, err
	}
}