Skip to content

Commit

Permalink
improve: optimize UserOnline algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Mmx233 committed Apr 5, 2024
1 parent 9a8b878 commit 8b9e062
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
43 changes: 19 additions & 24 deletions internal/service/LoginRecord.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package service

import (
"context"
"errors"
"github.com/Mmx233/daoUtil"
"github.com/ncuhome/GeniusAuthoritarian/internal/db/dao"
"github.com/ncuhome/GeniusAuthoritarian/internal/db/dto"
Expand Down Expand Up @@ -64,35 +63,31 @@ func (a LoginRecordSrv) UserOnline(uid uint, currentLoginID uint) ([]dto.LoginRe
if err != nil {
return nil, err
}
if len(validRecords) == 0 {
return validRecords, nil
}

var _redis = redis.NewRecordedToken()
var validCount int
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
ids := make([]uint64, len(validRecords))
for i, record := range validRecords {
err = _redis.NewStorePoint(uint64(record.ID)).Get(ctx, nil)
if err != nil {
if errors.Is(err, redis.Nil) {
validRecords[i].ID = 0
continue
}
return nil, err
}
validCount++
ids[i] = uint64(record.ID)
}
recordState, err := redis.NewRecordedToken().MPointGet(context.Background(), ids...)
if err != nil {
return nil, err
}

var result = make([]dto.LoginRecordOnline, validCount)
if validCount != 0 {
for i, record := range validRecords {
if record.ID != 0 {
if record.ID == currentLoginID {
record.IsMe = true
}
result[i] = record
}
pointer := 0
for i := 0; i < len(validRecords); i++ {
if recordState[i] == redis.Nil {
continue
}
validRecords[i].IsMe = validRecords[i].ID == currentLoginID
if i != pointer {
validRecords[pointer] = validRecords[i]
}
pointer++
}
return result, nil
return validRecords[0:pointer], nil
}

func (a LoginRecordSrv) OnlineRecordExist(uid, id uint, opts ...daoUtil.ServiceOpt) (bool, error) {
Expand Down
8 changes: 8 additions & 0 deletions pkg/tokenStore/tokenStore.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ func (a TokenStore[C]) CreateStorePoint(ctx context.Context, valid time.Duration
return id, a.CreateStorePointWithID(ctx, id, valid, claims)
}

func (a TokenStore[C]) MPointGet(ctx context.Context, ids ...uint64) ([]interface{}, error) {
keys := make([]string, len(ids))
for i, id := range ids {
keys[i] = a.genKey(id)
}
return a.client.MGet(ctx, keys...).Result()
}

func (a TokenStore[C]) NewStorePoint(id uint64) Point[C] {
return Point[C]{
s: a,
Expand Down

0 comments on commit 8b9e062

Please sign in to comment.