main.go 5.78 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/golang/protobuf/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/resolver"
	"google.golang.org/grpc/resolver/manual"
	"hilo-socketCenter/common"
	"hilo-socketCenter/common/mylogrus"
	"hilo-socketCenter/common/redisCli"
	"hilo-socketCenter/domain/model/rpc_m"
	"hilo-socketCenter/protocol/userCenter"
	"hilo-socketCenter/protocol/userProxy"
	"time"
)

iamhujiebin's avatar
iamhujiebin committed
22 23
const SEND_WORKER = 1       // 消费端协程数量
const MONITOR_LENGTH = 1000 // 队列告警数量
hujiebin's avatar
hujiebin committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
const SocketQueueSendGift = "socket:queue:send_gift"

var userClient userCenter.UserClient

type SendGiftMsg struct {
	SendUserId uint64                      `json:"sendUserId"`
	Msg        *userProxy.GlobalGiftBanner `json:"msg"`
}

var sendGiftChan chan *SendGiftMsg

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
}

// 初始化userCenterClient
func init() {
hujiebin's avatar
hujiebin committed
43 44 45 46 47
	redisKey := fmt.Sprintf("service:userCenter")
	ipPorts, err := redisCli.GetRedisCluster().ZRangeByScore(context.Background(), redisKey, &redis.ZRangeBy{
		Min: fmt.Sprintf("%d", time.Now().Add(-time.Second*15).Unix()), // 3倍心跳
		Max: "+inf",
	}).Result()
hujiebin's avatar
hujiebin committed
48
	if err != nil {
hujiebin's avatar
hujiebin committed
49 50 51
		failMsg := fmt.Sprintf("get service fail,svc:%v,err:%v", "userCenter", err)
		mylogrus.MyLog.Errorf(failMsg)
	} else if len(ipPorts) > 0 {
hujiebin's avatar
hujiebin committed
52
	}
hujiebin's avatar
hujiebin committed
53 54
	if len(ipPorts) <= 0 {
		ipPorts = []string{"127.0.0.1:50040"}
hujiebin's avatar
hujiebin committed
55 56
	}

hujiebin's avatar
hujiebin committed
57 58
	addresses := make([]resolver.Address, len(ipPorts))
	for i, s := range ipPorts {
hujiebin's avatar
hujiebin committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
		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")
	}
}

func main() {
	mylogrus.MyLog.Infof("cron sendGiftChan start")
	// 8核 n send + 4 blpop
	sendGiftChan = make(chan *SendGiftMsg, SEND_WORKER)
iamhujiebin's avatar
iamhujiebin committed
90
	for i := 0; i < 1; i++ {
hujiebin's avatar
hujiebin committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104
		go func() {
			deal()
		}()
	}
	for i := 0; i < SEND_WORKER; i++ {
		go func() {
			send()
		}()
	}
	go check()
	select {}
}

func check() {
iamhujiebin's avatar
iamhujiebin committed
105
	tick := time.NewTicker(time.Second * 30)
hujiebin's avatar
hujiebin committed
106 107 108 109
	defer tick.Stop()
	for {
		select {
		case <-tick.C:
JiebinHu's avatar
JiebinHu committed
110
			l, err := redisCli.GetRedisCluster().LLen(context.Background(), SocketQueueSendGift).Result()
hujiebin's avatar
hujiebin committed
111 112 113 114
			if err != nil {
				mylogrus.MyLog.Infof("cron sendGiftChan msg error,left %v-%v", l, err)
			}
			if l > MONITOR_LENGTH {
hujiebin's avatar
hujiebin committed
115 116 117 118 119 120
				mylogrus.MyLog.Infof("送礼横幅变化通知延迟,队列%s长度:%d", SocketQueueSendGift, l)
				//go func() {
				//	if sErr := dingding.SendDingRobot(dingding.ROBOTWEBHOOK, fmt.Sprintf("送礼横幅变化通知延迟,队列%s长度:%d", SocketQueueSendGift, l), true); sErr != nil {
				//		mylogrus.MyLog.Errorf("dingding msg fail:%v", sErr)
				//	}
				//}()
JiebinHu's avatar
JiebinHu committed
121
				n, err := redisCli.GetRedisCluster().Del(context.Background(), SocketQueueSendGift).Result()
iamhujiebin's avatar
iamhujiebin committed
122
				mylogrus.MyLog.Infof("del sendGiftChan msg queue:%v,n:%v,err:%v", SocketQueueSendGift, n, err)
hujiebin's avatar
hujiebin committed
123 124 125 126 127 128 129 130
			}
		}
	}
}

func deal() {
	for true {
		//不需要加锁,注意,阻塞。
hujiebin's avatar
hujiebin committed
131
		// 后进先出
JiebinHu's avatar
JiebinHu committed
132
		strs, err := redisCli.GetRedisCluster().BRPop(context.Background(), time.Second, SocketQueueSendGift).Result()
hujiebin's avatar
hujiebin committed
133 134 135 136 137 138 139
		if err != nil {
			if err != redis.Nil {
				mylogrus.MyLog.Errorf("cron sendGiftChan redisCli.GetRedis().BLPop err:+%v", err)
			}
		}
		if len(strs) >= 2 {
			content := strs[1]
JiebinHu's avatar
JiebinHu committed
140
			//mylogrus.MyLog.Infof("cron sendGiftChan content:%v", content)
hujiebin's avatar
hujiebin committed
141 142 143 144 145 146
			msg := new(SendGiftMsg)
			if err := json.Unmarshal([]byte(content), msg); err != nil {
				mylogrus.MyLog.Errorf("cron sendGiftChan Unmarshal err:%+v, content:%v", err, content)
			}
			sendGiftChan <- msg
		}
iamhujiebin's avatar
iamhujiebin committed
147
		time.Sleep(time.Second * 5) // 控制全服banner速率
hujiebin's avatar
hujiebin committed
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
	}
}

//var limiter = rate.NewLimiter(2000, 2000)

func send() {
	for msg := range sendGiftChan {
		//if err := limiter.Wait(context.Background()); err == nil {
		SendToUserCenter(msg.SendUserId, msg.Msg)
		//}
	}
}

// SendToUserCenter 发送群信令。入参是内部imGroupId,这里做转换
func SendToUserCenter(sendUserId uint64, msg *userProxy.GlobalGiftBanner) {
	if buffer, err := proto.Marshal(msg); err == nil {
		rspUids, err := broadcast(common.MsgTypeGlobalGiftBanner, buffer)

		//记录socket,注意闭包问题
		go func(userId uint64, msg *userProxy.GlobalGiftBanner, rspUids []uint64, err error) {
			buf, _ := json.Marshal(msg)
			rpc_m.AddRpcLog(common.MsgTypeGlobalGiftBanner, userId, string(buf[:]), rspUids, err)
		}(sendUserId, msg, rspUids, err)

		if err != nil {
			mylogrus.MyLog.Errorf("grpc GlobalGiftBanner send fail")
		} else {
JiebinHu's avatar
JiebinHu committed
175
			//mylogrus.MyLog.Info("grpc GlobalGiftBanner send success")
hujiebin's avatar
hujiebin committed
176 177 178 179 180 181 182
		}
	} else {
	}
}

//广播
func broadcast(msgType uint32, data []byte) ([]uint64, error) {
hujiebin's avatar
hujiebin committed
183
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
hujiebin's avatar
hujiebin committed
184 185 186 187 188 189 190 191 192
	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 {
JiebinHu's avatar
JiebinHu committed
193
		//mylogrus.MyLog.Infof("broadcast message res:%v", rsp)
hujiebin's avatar
hujiebin committed
194 195 196 197 198
		return rsp.FailedUids, err
	} else {
		return []uint64{}, err
	}
}