A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
feat(cache): upgrade cache interface
LinkinStars8a037f00db9c
diff --git a/cmd/main.go b/cmd/main.goindex 2a5ddaa1..5d166897 100644--- a/cmd/main.go+++ b/cmd/main.go@@ -1,6 +1,7 @@package answercmdimport (+ "context""fmt""os""time"@@ -39,7 +40,7 @@ var (// @name Authorizationfunc Main() {log.SetLogger(zap.NewLogger(- log.ParseLevel(logLevel), zap.WithName("answer"), zap.WithPath(logPath), zap.WithCallerFullPath()))+ log.ParseLevel(logLevel), zap.WithName("answer"), zap.WithPath(logPath)))Execute()}@@ -59,7 +60,7 @@ func runApp() {fmt.Println("answer Version:", constant.Version, " Revision:", constant.Revision)defer cleanup()- if err := app.Run(); err != nil {+ if err := app.Run(context.Background()); err != nil {panic(err)}}diff --git a/go.mod b/go.modindex d19dcb24..889935f4 100644--- a/go.mod+++ b/go.mod@@ -29,8 +29,8 @@ require (github.com/ory/dockertest/v3 v3.9.1github.com/robfig/cron/v3 v3.0.1github.com/scottleedavis/go-exif-remove v0.0.0-20230314195146-7e059d593405- github.com/segmentfault/pacman v1.0.4- github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20221219081300-f734f4a16aa0+ github.com/segmentfault/pacman v1.0.5-0.20230822075009-309985fb8700+ github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20230822075009-309985fb8700github.com/segmentfault/pacman/contrib/conf/viper v0.0.0-20221018072427-a15dd1434e05github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093754-b76aef1c1150github.com/segmentfault/pacman/contrib/log/zap v0.0.0-20221018072427-a15dd1434e05diff --git a/go.sum b/go.sumindex 6124c0a0..c404d30a 100644--- a/go.sum+++ b/go.sum@@ -642,10 +642,10 @@ github.com/scottleedavis/go-exif-remove v0.0.0-20230314195146-7e059d593405 h1:2igithub.com/scottleedavis/go-exif-remove v0.0.0-20230314195146-7e059d593405/go.mod h1:rIxVzVLKlBwLxO+lC+k/I4HJfRQcemg/f/76Xmmzsec=github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg=-github.com/segmentfault/pacman v1.0.4 h1:6UIXuMHUeYMWe5toflV9SXZQizRny1RczjZJLj9kul0=-github.com/segmentfault/pacman v1.0.4/go.mod h1:5lNp5REd8QMThmBUvR3Fi9Y3AsOB4GRq7soCB4QLqOs=-github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20221219081300-f734f4a16aa0 h1:4x0qG7H2M3qH7Yo2BhGrVlji1iTmRAWgINY/JyENeHs=-github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20221219081300-f734f4a16aa0/go.mod h1:rmf1TCwz67dyM+AmTwSd1BxTo2AOYHj262lP93bOZbs=+github.com/segmentfault/pacman v1.0.5-0.20230822075009-309985fb8700 h1:VqxiuNGQg86GEKxnzmJegZR2Ufr7EVXo68mdKaf+/MQ=+github.com/segmentfault/pacman v1.0.5-0.20230822075009-309985fb8700/go.mod h1:5lNp5REd8QMThmBUvR3Fi9Y3AsOB4GRq7soCB4QLqOs=+github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20230822075009-309985fb8700 h1:VZpexPTcr7sOxxYUGa/9cneyCESfisAhCNbaEuTpcwI=+github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20230822075009-309985fb8700/go.mod h1:rmf1TCwz67dyM+AmTwSd1BxTo2AOYHj262lP93bOZbs=github.com/segmentfault/pacman/contrib/conf/viper v0.0.0-20221018072427-a15dd1434e05 h1:BlqTgc3/MYKG6vMI2MI+6o+7P4Gy5PXlawu185wPXAk=github.com/segmentfault/pacman/contrib/conf/viper v0.0.0-20221018072427-a15dd1434e05/go.mod h1:prPjFam7MyZ5b3S9dcDOt2tMPz6kf7C9c243s9zSwPY=github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093754-b76aef1c1150 h1:OEuW1D7RGDE0CZDr0oGMw9Eiq7fAbD9C4WMrvSixamk=diff --git a/internal/repo/auth/auth.go b/internal/repo/auth/auth.goindex 440ec1f8..e73870be 100644--- a/internal/repo/auth/auth.go+++ b/internal/repo/auth/auth.go@@ -27,15 +27,15 @@ func NewAuthRepo(data *data.Data) auth.AuthRepo {// GetUserCacheInfo get user cache infofunc (ar *authRepo) GetUserCacheInfo(ctx context.Context, accessToken string) (userInfo *entity.UserCacheInfo, err error) {- userInfoCache, err := ar.data.Cache.GetString(ctx, constant.UserTokenCacheKey+accessToken)+ userInfoCache, exist, err := ar.data.Cache.GetString(ctx, constant.UserTokenCacheKey+accessToken)if err != nil {return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()}userInfo = &entity.UserCacheInfo{}- err = json.Unmarshal([]byte(userInfoCache), userInfo)- if err != nil {- return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()+ if !exist {+ return nil, nil}+ _ = json.Unmarshal([]byte(userInfoCache), userInfo)return userInfo, nil}@@ -81,15 +81,15 @@ func (ar *authRepo) SetUserStatus(ctx context.Context, userID string, userInfo *// GetUserStatus get user statusfunc (ar *authRepo) GetUserStatus(ctx context.Context, userID string) (userInfo *entity.UserCacheInfo, err error) {- userInfoCache, err := ar.data.Cache.GetString(ctx, constant.UserStatusChangedCacheKey+userID)+ userInfoCache, exist, err := ar.data.Cache.GetString(ctx, constant.UserStatusChangedCacheKey+userID)if err != nil {return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()}- userInfo = &entity.UserCacheInfo{}- err = json.Unmarshal([]byte(userInfoCache), userInfo)- if err != nil {- return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()+ if !exist {+ return nil, nil}+ userInfo = &entity.UserCacheInfo{}+ _ = json.Unmarshal([]byte(userInfoCache), userInfo)return userInfo, nil}@@ -104,16 +104,16 @@ func (ar *authRepo) RemoveUserStatus(ctx context.Context, userID string) (err er// GetAdminUserCacheInfo get admin user cache infofunc (ar *authRepo) GetAdminUserCacheInfo(ctx context.Context, accessToken string) (userInfo *entity.UserCacheInfo, err error) {- userInfoCache, err := ar.data.Cache.GetString(ctx, constant.AdminTokenCacheKey+accessToken)+ userInfoCache, exist, err := ar.data.Cache.GetString(ctx, constant.AdminTokenCacheKey+accessToken)if err != nil {err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()return}- userInfo = &entity.UserCacheInfo{}- err = json.Unmarshal([]byte(userInfoCache), userInfo)- if err != nil {- return nil, err+ if !exist {+ return nil, nil}+ userInfo = &entity.UserCacheInfo{}+ _ = json.Unmarshal([]byte(userInfoCache), userInfo)return userInfo, nil}@@ -144,7 +144,10 @@ func (ar *authRepo) RemoveAdminUserCacheInfo(ctx context.Context, accessToken st// AddUserTokenMapping add user token mappingfunc (ar *authRepo) AddUserTokenMapping(ctx context.Context, userID, accessToken string) (err error) {key := constant.UserTokenMappingCacheKey + userID- resp, _ := ar.data.Cache.GetString(ctx, key)+ resp, _, err := ar.data.Cache.GetString(ctx, key)+ if err != nil {+ return err+ }mapping := make(map[string]bool, 0)if len(resp) > 0 {_ = json.Unmarshal([]byte(resp), &mapping)@@ -157,7 +160,10 @@ func (ar *authRepo) AddUserTokenMapping(ctx context.Context, userID, accessToken// RemoveUserTokens Log out all users under this user idfunc (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainToken string) {key := constant.UserTokenMappingCacheKey + userID- resp, _ := ar.data.Cache.GetString(ctx, key)+ resp, _, err := ar.data.Cache.GetString(ctx, key)+ if err != nil {+ return+ }mapping := make(map[string]bool, 0)if len(resp) > 0 {_ = json.Unmarshal([]byte(resp), &mapping)diff --git a/internal/repo/captcha/captcha.go b/internal/repo/captcha/captcha.goindex a332523a..b055ff25 100644--- a/internal/repo/captcha/captcha.go+++ b/internal/repo/captcha/captcha.go@@ -43,19 +43,18 @@ func (cr *captchaRepo) SetActionType(ctx context.Context, unit, actionType, confreturn}-func (cr *captchaRepo) GetActionType(ctx context.Context, unit, actionType string) (actioninfo *entity.ActionRecordInfo, err error) {+func (cr *captchaRepo) GetActionType(ctx context.Context, unit, actionType string) (actionInfo *entity.ActionRecordInfo, err error) {now := time.Now()cacheKey := fmt.Sprintf("ActionRecord:%s@%s@%s", unit, actionType, now.Format("2006-1-02"))- actioninfo = &entity.ActionRecordInfo{}- res, err := cr.data.Cache.GetString(ctx, cacheKey)+ res, exist, err := cr.data.Cache.GetString(ctx, cacheKey)if err != nil {- err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()+ return nil, err}- err = json.Unmarshal([]byte(res), actioninfo)- if err != nil {- return actioninfo, nil+ actionInfo = &entity.ActionRecordInfo{}+ if exist {+ _ = json.Unmarshal([]byte(res), actionInfo)}- return actioninfo, nil+ return actionInfo, nil}func (cr *captchaRepo) DelActionType(ctx context.Context, unit, actionType string) (err error) {@@ -79,9 +78,12 @@ func (cr *captchaRepo) SetCaptcha(ctx context.Context, key, captcha string) (err// GetCaptcha get captcha from cachefunc (cr *captchaRepo) GetCaptcha(ctx context.Context, key string) (captcha string, err error) {- captcha, err = cr.data.Cache.GetString(ctx, key)+ captcha, exist, err := cr.data.Cache.GetString(ctx, key)if err != nil {- log.Debug(err)+ return "", err+ }+ if !exist {+ return "", fmt.Errorf("captcha not exist")}return captcha, nil}diff --git a/internal/repo/config/config_repo.go b/internal/repo/config/config_repo.goindex 0d426d70..07f4ce7f 100644--- a/internal/repo/config/config_repo.go+++ b/internal/repo/config/config_repo.go@@ -28,7 +28,7 @@ func NewConfigRepo(data *data.Data) config.ConfigRepo {func (cr configRepo) GetConfigByID(ctx context.Context, id int) (c *entity.Config, err error) {cacheKey := fmt.Sprintf("%s%d", constant.ConfigID2KEYCacheKeyPrefix, id)- if cacheData, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && len(cacheData) > 0 {+ if cacheData, exist, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && exist {c = &entity.Config{}c.BuildByJSON([]byte(cacheData))if c.ID > 0 {@@ -54,7 +54,7 @@ func (cr configRepo) GetConfigByID(ctx context.Context, id int) (c *entity.Confifunc (cr configRepo) GetConfigByKey(ctx context.Context, key string) (c *entity.Config, err error) {cacheKey := constant.ConfigKEY2ContentCacheKeyPrefix + key- if cacheData, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && len(cacheData) > 0 {+ if cacheData, exist, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && exist {c = &entity.Config{}c.BuildByJSON([]byte(cacheData))if c.ID > 0 {diff --git a/internal/repo/export/email_repo.go b/internal/repo/export/email_repo.goindex 33fb31fc..7c2dd952 100644--- a/internal/repo/export/email_repo.go+++ b/internal/repo/export/email_repo.go@@ -33,9 +33,12 @@ func (e *emailRepo) SetCode(ctx context.Context, code, content string, duration// VerifyCode verify the code if out of datefunc (e *emailRepo) VerifyCode(ctx context.Context, code string) (content string, err error) {- content, err = e.data.Cache.GetString(ctx, code)+ content, exist, err := e.data.Cache.GetString(ctx, code)if err != nil {- err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()+ return "", err}- return+ if !exist {+ return "", nil+ }+ return content, nil}diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.goindex 4f51e6f2..299b8451 100644--- a/internal/repo/question/question_repo.go+++ b/internal/repo/question/question_repo.go@@ -259,8 +259,8 @@ func (qr *questionRepo) SitemapQuestions(ctx context.Context, page, pageSize int// try to get sitemap data from cachecacheKey := fmt.Sprintf(constant.SiteMapQuestionCacheKeyPrefix, page)- cacheData, err := qr.data.Cache.GetString(ctx, cacheKey)- if err == nil && len(cacheKey) > 0 {+ cacheData, exist, err := qr.data.Cache.GetString(ctx, cacheKey)+ if err == nil && exist {_ = json.Unmarshal([]byte(cacheData), &questionIDList)return questionIDList, nil}diff --git a/internal/repo/site_info/siteinfo_repo.go b/internal/repo/site_info/siteinfo_repo.goindex 03c89416..95306fa8 100644--- a/internal/repo/site_info/siteinfo_repo.go+++ b/internal/repo/site_info/siteinfo_repo.go@@ -61,12 +61,14 @@ func (sr *siteInfoRepo) GetByType(ctx context.Context, siteType string) (siteInf}func (sr *siteInfoRepo) getCache(ctx context.Context, siteType string) (siteInfo *entity.SiteInfo) {- siteInfo = &entity.SiteInfo{}- siteInfoCache, err := sr.data.Cache.GetString(ctx, constant.SiteInfoCacheKey+siteType)+ siteInfoCache, exist, err := sr.data.Cache.GetString(ctx, constant.SiteInfoCacheKey+siteType)if err != nil {return nil}- _ = json.Unmarshal([]byte(siteInfoCache), siteInfo)+ siteInfo = &entity.SiteInfo{}+ if exist {+ _ = json.Unmarshal([]byte(siteInfoCache), siteInfo)+ }return siteInfo}diff --git a/internal/repo/user_external_login/user_external_login_repo.go b/internal/repo/user_external_login/user_external_login_repo.goindex 9c7c5e22..e6ab206a 100644--- a/internal/repo/user_external_login/user_external_login_repo.go+++ b/internal/repo/user_external_login/user_external_login_repo.go@@ -85,10 +85,13 @@ func (ur *userExternalLoginRepo) SetCacheUserExternalLoginInfo(// GetCacheUserExternalLoginInfo cache user info for external loginfunc (ur *userExternalLoginRepo) GetCacheUserExternalLoginInfo(ctx context.Context, key string) (info *schema.ExternalLoginUserInfoCache, err error) {- res, err := ur.data.Cache.GetString(ctx, constant.ConnectorUserExternalInfoCacheKey+key)+ res, exist, err := ur.data.Cache.GetString(ctx, constant.ConnectorUserExternalInfoCacheKey+key)if err != nil {return info, err}- _ = json.Unmarshal([]byte(res), &info)+ info = &schema.ExternalLoginUserInfoCache{}+ if exist {+ _ = json.Unmarshal([]byte(res), &info)+ }return info, nil}diff --git a/internal/service/auth/auth.go b/internal/service/auth/auth.goindex 9053a507..33e987eb 100644--- a/internal/service/auth/auth.go+++ b/internal/service/auth/auth.go@@ -41,6 +41,9 @@ func (as *AuthService) GetUserCacheInfo(ctx context.Context, accessToken string)if err != nil {return nil, err}+ if userCacheInfo == nil {+ return nil, nil+ }cacheInfo, _ := as.authRepo.GetUserStatus(ctx, userCacheInfo.UserID)if cacheInfo != nil {userCacheInfo.UserStatus = cacheInfo.UserStatusdiff --git a/internal/service/dashboard/dashboard_service.go b/internal/service/dashboard/dashboard_service.goindex e6b26701..829c3038 100644--- a/internal/service/dashboard/dashboard_service.go+++ b/internal/service/dashboard/dashboard_service.go@@ -95,12 +95,15 @@ func (ds *dashboardService) Statistical(ctx context.Context) (*schema.DashboardIreturn dashboardInfo, nil}-func (ds *dashboardService) getFromCache(ctx context.Context) (*schema.DashboardInfo, error) {- infoStr, err := ds.data.Cache.GetString(ctx, schema.DashboardCacheKey)+func (ds *dashboardService) getFromCache(ctx context.Context) (dashboardInfo *schema.DashboardInfo, err error) {+ infoStr, exist, err := ds.data.Cache.GetString(ctx, schema.DashboardCacheKey)if err != nil {return nil, err}- dashboardInfo := &schema.DashboardInfo{}+ dashboardInfo = &schema.DashboardInfo{}+ if !exist {+ return dashboardInfo, nil+ }if err = json.Unmarshal([]byte(infoStr), dashboardInfo); err != nil {return nil, err}diff --git a/internal/service/export/email_service.go b/internal/service/export/email_service.goindex 134a4fb2..0f0985f5 100644--- a/internal/service/export/email_service.go+++ b/internal/service/export/email_service.go@@ -145,7 +145,7 @@ func (es *EmailService) Send(ctx context.Context, toEmailAddr, subject, body strfunc (es *EmailService) VerifyUrlExpired(ctx context.Context, code string) (content string) {content, err := es.emailRepo.VerifyCode(ctx, code)if err != nil {- log.Warn(err)+ log.Error(err)}return content}diff --git a/internal/service/notification/notification_service.go b/internal/service/notification/notification_service.goindex 25d8444e..98475e19 100644--- a/internal/service/notification/notification_service.go+++ b/internal/service/notification/notification_service.go@@ -46,13 +46,13 @@ func (ns *NotificationService) GetRedDot(ctx context.Context, req *schema.GetRedredBot := &schema.RedDot{}inboxKey := fmt.Sprintf("answer_RedDot_%d_%s", schema.NotificationTypeInbox, req.UserID)achievementKey := fmt.Sprintf("answer_RedDot_%d_%s", schema.NotificationTypeAchievement, req.UserID)- inboxValue, err := ns.data.Cache.GetInt64(ctx, inboxKey)+ inboxValue, _, err := ns.data.Cache.GetInt64(ctx, inboxKey)if err != nil {redBot.Inbox = 0} else {redBot.Inbox = inboxValue}- achievementValue, err := ns.data.Cache.GetInt64(ctx, achievementKey)+ achievementValue, _, err := ns.data.Cache.GetInt64(ctx, achievementKey)if err != nil {redBot.Achievement = 0} else {diff --git a/plugin/cache.go b/plugin/cache.goindex 993f3fe0..da6ee69d 100644--- a/plugin/cache.go+++ b/plugin/cache.go@@ -8,12 +8,14 @@ import (type Cache interface {Base- GetString(ctx context.Context, key string) (string, error)- SetString(ctx context.Context, key, value string, ttl time.Duration) error- GetInt64(ctx context.Context, key string) (int64, error)- SetInt64(ctx context.Context, key string, value int64, ttl time.Duration) error- Del(ctx context.Context, key string) error- Flush(ctx context.Context) error+ GetString(ctx context.Context, key string) (data string, exist bool, err error)+ SetString(ctx context.Context, key, value string, ttl time.Duration) (err error)+ GetInt64(ctx context.Context, key string) (data int64, exist bool, err error)+ SetInt64(ctx context.Context, key string, value int64, ttl time.Duration) (err error)+ Increase(ctx context.Context, key string, value int64) (data int64, err error)+ Decrease(ctx context.Context, key string, value int64) (data int64, err error)+ Del(ctx context.Context, key string) (err error)+ Flush(ctx context.Context) (err error)}var (