diff --git a/handler/im.go b/handler/im.go index cb3cd7b..ab7b407 100644 --- a/handler/im.go +++ b/handler/im.go @@ -540,6 +540,7 @@ func ServerSendMsgV2(c *gin.Context) { //设置用户在线状态 worker.SetRedisWithExpire("user_"+strconv.Itoa(user_id)+"_status_v2", "1", time.Second*60) worker.SetRedisBitmap("im2_online_users", int64(user_id), 1) + worker.SetRedisSetAdd("im2_online_users_set", strconv.Itoa(user_id)) //发送消息 key := "user_" + strconv.Itoa(user_id) + "_msg_ids" @@ -577,6 +578,7 @@ func ServerSendMsgV2(c *gin.Context) { if err2 != nil { worker.SetRedisWithExpire("user_"+strconv.Itoa(user_id)+"_status_v2", "0", time.Second*3600) worker.SetRedisBitmap("im2_online_users", int64(user_id), 0) + worker.SetRedisSetRemove("im2_online_users_set", strconv.Itoa(user_id)) clientsMux.Lock() delete(clients, ws) clientsMux.Unlock() diff --git a/service/imService.go b/service/imService.go index c19799b..6aa1e42 100644 --- a/service/imService.go +++ b/service/imService.go @@ -84,19 +84,18 @@ func CreateGeneralMessageService(from_id, to_id, msg_type, group_id int, content err, id = dao.CreateGeneralMessage(from_id, to_id, msg_type, 0, group_id, content) //获取群里的用户 - user_ids := worker.GetRedisSetMembers("group_" + strconv.Itoa(group_id) + "_users") + //user_ids := worker.GetRedisSetMembers("group_" + strconv.Itoa(group_id) + "_users") + //在线的用户群id + online_user_ids := worker.GetRedisSetIntersect("im2_online_users_set", "group_"+strconv.Itoa(group_id)+"_users") //users := dao.FindGroupUsers(group_id) - for _, user_id := range user_ids { + for _, user_id := range online_user_ids { //判断是否是自己,不是则存入redis id_, _ := strconv.Atoi(user_id) if id_ == from_id { continue } - res := worker.GetRedis("user_" + user_id + "_status_v2") - if res == "1" { - //在线,存入redis - worker.PushRedisListWithExpire("user_"+user_id+"_msg_ids", strconv.Itoa(int(id)), time.Second*300) - } + //在线,存入redis + worker.PushRedisListWithExpire("user_"+user_id+"_msg_ids", strconv.Itoa(int(id)), time.Second*300) } case 3: //user := dao.FindUserByID(to_id) diff --git a/worker/redis.go b/worker/redis.go index b716737..e2695bd 100644 --- a/worker/redis.go +++ b/worker/redis.go @@ -303,6 +303,17 @@ func SetRedisSetRemove(key string, value string) bool { return true } +// 获取两个set的交集 +func GetRedisSetIntersect(key1 string, key2 string) []string { + ctx := context.Background() + val, err := redisClient.SInter(ctx, key1, key2).Result() + if err != nil { + fmt.Println("Error getting key: %v", err) + return nil + } + return val +} + // 查看set是否包含元素 func IsContainSet(key string, value string) bool { ctx := context.Background()