From 470bd0428c11eb0675f028e30143d715b4c4a640 Mon Sep 17 00:00:00 2001 From: withchao <993506633@qq.com> Date: Wed, 25 Oct 2023 18:02:05 +0800 Subject: [PATCH] feat: im admin token cache --- pkg/common/apicall/caller.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/pkg/common/apicall/caller.go b/pkg/common/apicall/caller.go index 93cef4b3d..6bd25528f 100644 --- a/pkg/common/apicall/caller.go +++ b/pkg/common/apicall/caller.go @@ -16,7 +16,8 @@ package apicall import ( "context" - "fmt" + "sync" + "time" "github.com/OpenIMSDK/chat/pkg/common/config" "github.com/OpenIMSDK/protocol/auth" @@ -40,7 +41,11 @@ type CallerInterface interface { FriendUserIDs(ctx context.Context, userID string) ([]string, error) } -type Caller struct{} +type Caller struct { + token string + timeout time.Time + lock sync.Mutex +} func NewCallerInterface() CallerInterface { return &Caller{} @@ -58,11 +63,20 @@ func (c *Caller) ImportFriend(ctx context.Context, ownerUserID string, friendUse } func (c *Caller) ImAdminTokenWithDefaultAdmin(ctx context.Context) (string, error) { - return c.UserToken(ctx, config.GetDefaultIMAdmin(), constant.AdminPlatformID) + c.lock.Lock() + defer c.lock.Unlock() + if c.token == "" || c.timeout.Before(time.Now()) { + token, err := c.UserToken(ctx, config.GetDefaultIMAdmin(), constant.AdminPlatformID) + if err != nil { + return "", err + } + c.token = token + c.timeout = time.Now().Add(time.Minute * 5) + } + return c.token, nil } func (c *Caller) UserToken(ctx context.Context, userID string, platformID int32) (string, error) { - fmt.Println(*config.Config.Secret) resp, err := userToken.Call(ctx, &auth.UserTokenReq{ Secret: *config.Config.Secret, PlatformID: platformID,